我正在使用Spring data jpa
和spring mvc
而且我注意到我的对象contact
会自动在数据库中更新。
这是我的代码:
@Transactional
@Controller
public class ContactController {
@RequestMapping(value="/update_contact ")
public @ResponseBody
String update_contact (...) {
...
Contact contact = contactrespository.findOne(idcontact);
contact.setName(...);
...
}
}
而且,当我检查数据库时,未执行contactrespository.save(idcontact);
我的contact
更改!
你能解释一下为什么吗?
对象有多种状态:
在这种情况下,更改将提交给联系,因为它是在事务内修改的持久对象,因为您的控制器带有注释,@Transactional
因此它与休眠会话相关联。
Controller
用Transactional
注解注释不是一个好习惯,最好在服务层中使用,我们repository
在控制器层调用not
@Controller
public class MyController{
@Autowired
private MyService service;
@RequestMapping ....
public Contact findContact(String name, ....){
Contact contact = service.get(...);
// other logic
}
}
@Service
public class MyService{
@Autowired
private MyRepository repository;
@Transactional(propagation=Propagation.SUPPORTS)
public Contact get(long id){
// better throw a notFuondException in here
return repository.findOne(id);
}
//same for other method like create and update with @Transactional REQUIRED NEW or REQUIRED propagation
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句