1 事物管理
在service层
在开启事物的方法上添加@Transactional 注解即可
package cn.dingyi.service;
import cn.dingyi.dao.UserDao;
import cn.dingyi.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
/**
* author:dingyi
* time:2019/8/23 0023 11:41
*/
@Service
public class UserService {
@Autowired
UserDao userDao;
@Transactional
public void updateName(){
//根据id 查询用户信息
Optional<User> byId = userDao.findById(1);
User user = byId.get();
// 修改名字
user.setName("桃谷绘里香");
userDao.save(user);
}
}
如果springBoot版本是2.0以下
需要 在启动类上添加注解@EnableTransactionManagement
一般情况下启动类有两个注解:
package cn.dingyi;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* author:dingyi
* time:2019/8/22 0022 10:44
*/
@SpringBootApplication
@MapperScan(basePackages = "cn.dingyi.mapper")
public class DyApplication {
public static void main(String[] args) {
SpringApplication.run(DyApplication.class,args);
}
}