【Android免費音樂下載app】【佳語音樂下載】建議最少2.0.3版本。最新版本:
https://gitlab.com/gaopinqiang/checkversion/raw/master/Music_Download.apk
Spring Boot 使用事務非常簡單;
- 1、在入口類中使用註解 @EnableTransactionManagement 開啓事務支持;
- 2、在訪問數據庫的Service方法上添加註解 @Transactional 即可;
示例:
1、在Application中加上開啓事務的註解
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;
//開啓Spring事務,測試發現不加也是生效的
@EnableTransactionManagement
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
2、在StudentController中增加一個更新數據庫操作的方法,在方法上加註解
@Transactional //表明這個方法是有事務的,如果出現異常就會回滾
@RequestMapping("/updateById")
public @ResponseBody String updateById(){
Student student = new Student();
student.setId(1);
student.setAge(31);
student.setName("qiang-transactional");
int i = studentService.updateById(student);
int zero = 10 / 0;//測試事務,報個異常,看數據庫操作是否回滾
return "修改記錄條數 = " + i;
}
3、Service Mapper 和xml實現
StudentService:
package com.example.mybatis.service;
import com.example.mybatis.model.Student;
import java.util.List;
import java.util.Map;
public interface StudentService {
int updateById(Student student);
}
StudentServiceImpl:
package com.example.mybatis.service.impl;
import com.example.mybatis.mapper.StudentMapper;
import com.example.mybatis.model.Student;
import com.example.mybatis.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentMapper studentMapper;
@Override
public int updateById(Student student) {
return studentMapper.updateById(student);
}
}
StudentMapper.java:
package com.example.mybatis.mapper;
import com.example.mybatis.model.Student;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
@Mapper
public interface StudentMapper {
int updateById(@Param(value = "student") Student student);//傳遞一個Student類型的參數
}
StudentMapper.xml:(這裏我們演示了使用parameterType參數)
<update id="updateById" parameterType="com.example.mybatis.model.Student">
update t_person
<set>
<if test="student.name != null">
name = #{student.name},
</if>
<if test="student.age != null">
age = #{student.age},
</if>
<if test="student.location != null">
location = #{student.location},
</if>
</set>
where
id = #{student.id}
</update>
(這裏我們演示了使用parameterType參數),取參數的時候使用 student.name這樣的方式。
4、測試
在瀏覽器中輸入:http://localhost:8080/updateById
Whitelabel Error Page This application has no explicit mapping for
/error, so you are seeing this as a fallback.Sat May 16 10:30:58 CST 2020 There was an unexpected error
(type=Internal Server Error, status=500). / by zero
查看數據庫,並沒有更新成功,表明事務生效了。
沒有異常截圖:
構造一個異常運行截圖: