本文使用的springboot+mybatis作为演示,相关配置查看上一篇springboot整合mybatis
1.实体类
//使用lombok注解生成getter setter等
@Data
public class SysUser {
private Long id;
private String username;
private String nickname;
private Integer age;
}
2.mapper接口
public interface SysUserMapper {
SysUser selectById(long id);
//在注解中写sql和xml中写sql都可以
@Update("update sys_user set age = #{age} where id = #{id}")
int updateAgeById(@Param("age") int age, @Param("id") long id);
}
3.mapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="demo.springboot.mybatis.dao.SysUserMapper" >
<resultMap id="BaseResultMap" type="demo.springboot.mybatis.domain.SysUser" >
<id column="id" property="id" jdbcType="BIGINT" />
<result column="username" property="username" jdbcType="VARCHAR" />
<result column="nickname" property="nickname" jdbcType="VARCHAR" />
<result column="age" property="age" jdbcType="INTEGER" />
</resultMap>
<select id="selectById" parameterType="long" resultMap="BaseResultMap">
select
*
from
sys_user
where id = #{id}
</select>
</mapper>
4.service
@Service
public class UserService {
@Autowired
private SysUserMapper userMapper;
//只需要在方法上加@Transactional注解即可,增删改操作如果出现错误就会回滚
@Transactional(rollbackFor = RuntimeException.class)
public void updateUserAge(){
userMapper.updateAgeById(40, 1L);
//模拟出现异常
int a = 1/0;
}
}
5.测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class MybatisApplicationTests {
@Autowired
private UserService userService;
@Test
public void testTransactional(){
//调用service前打印用户信息
System.out.println(userMapper.selectById(1L));
//捕获异常,避免程序结束
try {
userService.updateUserAge();
}catch (RuntimeException e){
}
//调用service后打印用户信息
System.out.println(userMapper.selectById(1L));
}
}
控制台打印:
SysUser(id=1, username=admin, nickname=admin, age=30)
SysUser(id=1, username=admin, nickname=admin, age=30)
调用service前年龄是30,service中将年龄修改成40,然后抛出异常,调用完service后由于事务回滚,年龄还是30
作者公众号
