- 事务在项目开发过程非常重要,涉及到数据的一致性的问题,不容马虎!
- 事务管理是企业级应用程序开发中必备技术,用来确保数据的完整性和一致性。
事务就是把一系列的动作当成一个独立的工作单元,这些动作要么全部完成,要么全部不起作用。
事务四个属性ACID
- 原子性(atomicity)
- 事务是原子性操作,由一系列动作组成,事务的原子性确保动作要么全部完成,要么完全不起作用。
- 一致性
- 一旦所有事务动作完成,事务就要被提交。数据和资源处于一种满足业务规则的一致性状态中
- 隔离性
- 可能多个事务会同时处理相同的数据,因此每个事务都应该与其他事务隔离开来,防止数据损坏
- 持久性
- 事务一旦完成,无论系统发生什么错误,结果都不会受到影响。通常情况下,事务的结果被写到持久化存储器中
- 实体类
@Data
public class User {
private int id;
private String name;
private String pwd;
}
- 包的导入
spring-study com.kuang 1.0-SNAPSHOT 4.0.0 spring-11-transaction junit junit 4.13.2 mysql mysql-connector-java 8.0.26 org.mybatis mybatis 3.5.7 org.springframework spring-webmvc 5.3.9 org.springframework spring-jdbc 5.3.9 org.aspectj aspectjweaver 1.9.7 org.mybatis mybatis-spring 2.0.6 org.projectlombok lombok 1.18.20 src/main/resources ***.xml true src/main/java ***.xml true
- mapper接口和mapper文件
UserMapper接口
public interface UserMapper {
public List selectUser();
}
mapper文件
UserMapperImpl.java实现类
public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper{
@Override
public List selectUser() {
UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
return mapper.selectUser();
}
}
- 配置文件
db.properties
//配置文件优先级问题(配置文件优先)。新特性:使用占位符 driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8 username=root password=12345678
mybatis-config.xml
spring-dao.xml
UserMapper.xml
3.测试类
public class MyTest { @Test public void test() throws IOException { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); UserMapper userMapper = context.getBean("userMapper", UserMapper.class); Listusers = userMapper.selectUser(); for (User user : users) { System.out.println(user); } } } 注意点:小程序涉及到的数据库和表,在以前的文章中有,这个小程序通过对用户的添加和删除来验证事务的特性。



