spring與mybatis整合及事務控制
阿新 • • 發佈:2018-12-31
一. 簡介
本文將會使用spring整合mybatis, 並新增事務管理, 以此為記, 方便以後查閱。
二. 例子
1. 程式碼結構圖:
2. 建表語句:
3. 實體類:DROP DATABASE test; CREATE DATABASE test; USE test; CREATE TABLE USER( id VARCHAR(36) PRIMARY KEY, username VARCHAR(64), address VARCHAR(128) ) INSERT INTO USER (id, username, address) VALUES("001", "zhangsan", "Wuhan"); INSERT INTO USER (id, username, address) VALUES("002", "lisi", "Shanghai");
public class User {
private String id;
private String uname;
private String address;
@Override
public String toString() {
return "id: " + id + ", uname: " + uname + ", address: " + address;
}
}
// 省略getter與setter方法
4. 實體對映配置:user.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.zdp.domain.User"> <resultMap type="User" id="userBean"> <id column="id" property="id"/> <result column="username" property="uname"/> <result column="address" property="address"/> </resultMap> <select id="selectUserById" parameterType="string" resultMap="userBean"> select * from user where id = #{id} </select> <update id="updateUserByCondition" parameterType="User"> update user <set> <if test="uname != null"> username = #{uname} , </if> <if test="address != null"> address = #{address} </if> </set> where id = #{id} </update> </mapper>
動態更新user
5. service介面:public interface UserService {
void updateUser(User user);
}
6. service實現:
public class UserServiceImpl implements UserService { private UserDao userDao; public void setUserDao(UserDao userDao) { this.userDao = userDao; } @Override public void updateUser(User user) { userDao.updateUser(user); System.out.println(1/0); // 執行時異常 } }
7. dao介面:
public interface UserDao {
User findUserById(String id);
void updateUser(User user);
}
8. dao實現:
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {
@Override
public User findUserById(String id) {
SqlSession sqlSession = super.getSqlSession();
User user = (User) sqlSession.selectOne(User.class.getName() + ".selectUserById", id);
return user;
}
@Override
public void updateUser(User user) {
super.getSqlSession().update(User.class.getName() + ".updateUserByCondition", user);
}
}
9. mybatis全域性配置:sqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<typeAlias type="com.zdp.domain.User" alias="User"/>
</typeAliases>
<mappers>
<!-- 對映檔案的位置 -->
<mapper resource="com/zdp/domain/User.xml" />
</mappers>
</configuration>
10. spring配置:ApplicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!-- 配置資料來源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///test"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<!-- session工廠 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- mybatis總配置檔案的位置 -->
<property name="configLocation" value="classpath:sqlMapConfig.xml"/>
</bean>
<!-- 配置事務管理 -->
<bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="find*" read-only="true" />
<tx:method name="get*" read-only="true" />
<tx:method name="select*" read-only="true" />
</tx:attributes>
</tx:advice>
<aop:config>
<!-- 第一個"*"代表所有類, 第二個"*"代表所有方法, ".."代表任意引數 -->
<aop:pointcut id="pointcut" expression="execution(* com.zdp.service.*.*(..))" />
<!-- 把事務控制在service層 -->
<aop:advisor pointcut-ref="pointcut" advice-ref="transactionAdvice" />
</aop:config>
<!-- 業務處理 -->
<bean id="userDao" class="com.zdp.dao.impl.UserDaoImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
<bean id="userService" class="com.zdp.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"/>
</bean>
</beans>
11. junit測試:
public class SpringTest {
private ApplicationContext context;
@Before
public void sprintInit() {
context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
}
@Test
public void testFindUserById() {
UserDao userDao = (UserDao) context.getBean("userDao");
User user = userDao.findUserById("001");
System.out.println(user);
}
@Test
public void testUpdateUser() {
UserService userService = (UserService) context.getBean("userService");
User user = new User();
user.setId("001");
user.setUname("zhangsan1");
userService.updateUser(user);
}
}