对象自动在数据库中更新

时间:2014-07-12 00:21:23

标签: hibernate spring-data

我正在使用Spring data jpaspring 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已被更改! 你能解释一下为什么吗?

1 个答案:

答案 0 :(得分:3)

对象有很多states

  • 持久性:持久化实例在数据库中具有表示形式,并且具有标识符值,并且与Hibernate会话相关联。
  • 分离:分离的实例是一个持久的对象,但其会话已关闭。
  • transient :如果一个对象刚刚使用new运算符进行实例化,并且它与Hibernate会话无关,则该对象是瞬态的。

在此上下文中,更改将提交到联系,因为它是在事务中已修改的持久对象,因为您的控制器使用@Transactional注释,因此它与Hibernate会话关联。

使用Controller注释注释Transactional不是一个好习惯,最好在我们调用repository而不是在控制器层中的服务层上使用

    @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
   }