程序涉及到对数据库的增删改的操作时,需要事务的支持,
否则数据库里就会有许多脏数据;
一般增删改业务逻辑都是在service层进行处理,所以对事务的处理也放在service层
使用注解 @Transactional标记需要事务处理的方法
@Service
public class EmployJpaService {
@Autowired
private EmployeeJpaReposity employeeJpaReposity;
/**
* 保存
*
* @param employees
* @return
*/
@Transactional
public List<Employee> save(List<Employee> employees) {
List<Employee> employeeList = employeeJpaReposity.save(employees);
return employeeList;
}
/**
* 修改
* <p>
* 判断是否存在
* 不存在 插入
* 存在 删除
*
* @param employee
*/
@Transactional
public void update(Employee employee) {
Integer id = employee.getEmpno();
boolean exists = employeeJpaReposity.exists(id);
if (exists) {
employeeJpaReposity.delete(employee);
}else {
employeeJpaReposity.save(employee);
}
}
}
----------------------------
测试:
@Test
public void testTransaction(){
Employee employee = new Employee();
employee.setEmpno(1234);
employee.setEname("noddles");
employee.setSal(100.0);
employee.setJob("coder");
employee.setDeptno(20);
employee.setHiredate(new Date(System.currentTimeMillis()));
employee.setMgr(200);
employee.setComm(100.0);
List<Employee> employees = Arrays.asList(employee);
employJpaService.save(employees);
Employee one = employeeJpaReposity.findOne(1234);
System.out.println("更新操作前---------------");
System.out.println(one);
boolean exists = employeeJpaReposity.exists(1234);
System.out.println("------------->"+exists);
employJpaService.update(employee);
exists = employeeJpaReposity.exists(1234);
System.out.println("------------->"+exists);
one = employeeJpaReposity.findOne(1234);
System.out.println("更新操作后---------------");
System.out.println(one);
}
-------------------------------------------------------------------------
测试结果:
更新操作前---------------
Employee{empno=1234, ename='noddles', job='coder', mgr=200, hiredate=2018-02-07, sal=100.0, comm=100.0, deptno=20}
------------->true
------------->false
更新操作后---------------
null
由于 JpaRepository接口中没提供update 方法,需要update 操作 还需 使用@Query注解,但要在之前加上
@Modifying注解,标识这个是update 或者delete操作!需要事务支持。
定义接口:
//更新工资
@Modifying
@Query(nativeQuery = true,value = "update EMP set sal=?1 where empno=?2")
public void updateSal(Double sal,Integer empno);
service层:
@Transactional
public void upateSal(Double sal,Integer enpno){
employeeJpaReposity.updateSal(sal,enpno);
}
测试:
@Test
public void testUpdateSal(){
Employee one = employeeJpaReposity.findOne(1234);
System.out.println("---------更新前--------->"+one);
employJpaService.upateSal(1200.0,1234);
one = employeeJpaReposity.findOne(1234);
System.out.println("---------更新后--------->"+one);
}
------------------------------------
测试结果:
---------更新前--------->Employee{empno=1234, ename='noddles', job='coder', mgr=200, hiredate=2018-02-07, sal=100.0, comm=100.0, deptno=20}
---------更新后--------->Employee{empno=1234, ename='noddles', job='coder', mgr=200, hiredate=2018-02-07, sal=1200.0, comm=100.0, deptno=20}