spring与mybatis集成和事务控制

时间:2024-04-23 08:07:11

一个. 基本介绍

本文将使用spring整合mybatis, 并加入事务管理, 以此为记, 方便以后查阅。

二. 样例

1. 代码结构图:

spring与mybatis集成和事务控制

2. 建表语句:

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");

3. 实体类:

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);
}
}

版权声明:本文博客原创文章,博客,未经同意,不得转载。