【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
查看数据库,并没有更新成功,表明事务生效了。
没有异常截图:
构造一个异常运行截图: