目录
一、事务配置
1、事务的特性
在我们进行事务配置之前,我们需要先对事务的特性了解一下,事务的特性(ACID)
原子性(A):事务是最小的单位,不可再分
一致性(C):事务要么都成功,要么都失败
隔离性(I):事务之间不会产生影响
持久性(D):事务处理后的数据要能够进行持久化的-保存在本地磁盘文件中。
从事务的特性可以知道我们想要达到的效果就是当我们对数据库进行操作时,当某一方操作失败时我们都不能对数据库的数据进行修改,这样才符合实际的情况。
举个例子
书写两个添加方法
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import com.DJX.bean.Student;
@Repository
public class StudentDao {
@Autowired//自动注入
private JdbcTemplate jdbcTemplate;
public int add(Student student) {
return jdbcTemplate.update("insert into student (NAME,PASSWORD) VALUES(?,?)",student.getName(),student.getPassword());
}
public int add1(Student student) {
return jdbcTemplate.update("insert into student VALUES(?,?,?)",student.getId(),student.getName(),student.getPassword());
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.DJX.Dao.StudentDao;
import com.DJX.bean.Student;
@Service
public class StudentService {
@Autowired
private StudentDao studentDao;
public void save() {
Student student = new Student("亚索","123");
studentDao.add(student);
Student student1 = new Student("皇子","1245");
student1.setId(21);
studentDao.add1(student1);
}
}
我们先打开数据库,可以看到21已经存在了
我们添加测试类
package com.DJX.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.DJX.service.StudentService;
public class StudentTest {
@Test
public void test() {
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
StudentService student = context.getBean(StudentService.class);
student.save();
}
}
执行测试类之后再一次打开数据库
一方添加失败另一个却添加成功了,这明显不是我们想要的效果,所以我们可以通过事务来对它进行约束。
2、通过注释实现事务
我们只需要在配置xml文件中加入这段代码
<!-- 此处的dataSource 为数据源配置-->
<bean id="transactionManager" class="org.springframework.jdbc.support.JdbcTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 使用@Transactional 注解必须开启配置-->
<tx:annotation-driven transaction-manager="transactionManager"/>
然后在业务层添加@Transactional实现事务即可
package com.DJX.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.DJX.Dao.StudentDao;
import com.DJX.bean.Student;
@Service
@Transactional
public class StudentService {
@Autowired
private StudentDao studentDao;
public void save() {
Student student = new Student("亚索","123");
studentDao.add(s