使用註解模式不需要配置文件,也不需要配置事務配置類或者方法,只需要使用“@Transcation”註解引入到相對應的位置即可實現事務回滾功能。
1.引入pom.xml
<!-- 事物 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</dependency>
2.在controller裏面使用事務註解(因爲service和接口層都是直接操作數據庫的方法,一般需要多個操作或者循環的Controller才需要事務支持,如果是mybatis批量操作數據庫語句也不需要事務)
事務作用域一般常見的分成兩種:
①定義在類上面 :所有的方法都支持事務
②定義在方法上 :只有該方法支持事務
package com.Transaction.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.Transaction.entity.Alarmtype;
import com.Transaction.mapper.AlarmtypeMapper;
import com.Transaction.service.AlarmtypeService;
@Controller
//@Transactional //事務級別,如果該類中同時操作多個方法,只要失敗則全部回滾
public class AlarmtypeController {
@Autowired
AlarmtypeMapper alarmtypeMapper;
@Autowired
AlarmtypeService alarmtypeService;
@RequestMapping("index")
public synchronized String index(){
//List<Alarmtype> list = alarmtypeMapper.getAlarmtypeList();
List<Alarmtype> list = alarmtypeService.findAll();
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).getId()+"--"+list.get(i).getAlarmname());
}
return "index";
}
//批量插入
@RequestMapping("addBatch")
@ResponseBody
@Transactional//對整個方法進行事務處理,方法體內只要有一個方法沒執行成功則全部回滾
public synchronized int addBatch(){
Alarmtype alarmtype = new Alarmtype();
Alarmtype updatealarmtype = new Alarmtype();
updatealarmtype.setId(1);
updatealarmtype.setAlarmname("修改前輪故障");
alarmtypeMapper.updateAlarmtypeById(updatealarmtype);
int result = 0;
try {
for (int i = 0; i < 5; i++) {
if(i==2){
//alarmname在數據庫中長度不超過50,賦值超過50報異常 Data too long
alarmtype.setAlarmname("測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試");
alarmtype.setAlarmtypeid(i);
}else{
alarmtype.setAlarmname("測試"+i);
alarmtype.setAlarmtypeid(i);
}
result = alarmtypeMapper.addAlarmtype(alarmtype);
}
}catch (Exception e) {
e.printStackTrace();
}
return result;
}
@RequestMapping("test")
@ResponseBody
public synchronized String test(){
return "test";
}
}
補充:在spring boot配置文件使用默認配置的情況下,如果使用try catch方法處理,如果發生異常,catch體裏面的操作數據庫的方法實際測試顯示不執行,會提示有回滾操作,所以需要捕捉錯誤信息並插入自定義數據庫表單的時候是不會執行的。