Hibernate使用EntityManager进行更新 [英] Hibernate update with EntityManager

查看:136
本文介绍了Hibernate使用EntityManager进行更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Hibernate 4.1.7并尝试更新对象,但没有文档说明它应该如何完成。目前,我正在这样做:

  Person person = personDao.getPersonById(1); 
person.setAge(23);
person.setLastname(McName);
person = personDao.update(person);

In PersonDao更新如下:

  public Person update(Person person){
return entityManager.merge(person);
}

In PersonDao getPersonById是:

  public Person getPersonById(int id){
personQuery = entityManager.createNamedQuery(Person.findPerson,Person.class);
personQuery.setParameter(id,id);
return personQuery.getSingleResult();
}

另外我已经在Person类中定义了命名查询并且在这里:

  @NamedQuery(name =Person.findPerson,query =SELECT p FROM Person p WHERE p.id =:id)

通过使用我的Person不会被更新,我应该如何使用hibernate实现更新?

解决方案

您可能会弹出两种情况。您可能需要更改该对象的一个​​属性,只有该属性。



如果您想要使用该方法:查找,修改,刷新,提交。

  em.find(Person.class,person.getId())
person.setStatus(ACTIVE);
em.commit(); //如果刷新模式为COMMIT或AUTO,则隐式刷新。

您可能希望使用对象属性来更新该项目。



如果您想要使用方法merge,则可以修改,刷新,提交。

  em.merge(人); 
//如果您愿意,可以修改人员。
em.commit(); //如果刷新模式为COMMIT或AUTO,则隐式刷新。


I am using Hibernate 4.1.7 and trying to update object, but theres no documentation how it should be done. Currently, I am doing this:

    Person person = personDao.getPersonById(1);
    person.setAge(23);
    person.setLastname("McName");
    person = personDao.update(person);

In PersonDao update looks like:

    public Person update(Person person) {
      return entityManager.merge(person);
    }

In PersonDao getPersonById is:

    public Person getPersonById(int id) {
      personQuery = entityManager.createNamedQuery("Person.findPerson", Person.class);
      personQuery.setParameter("id", id);
      return personQuery.getSingleResult();
    }

Also I have defined named query inside Person class and is here:

    @NamedQuery(name="Person.findPerson", query="SELECT p FROM Person p WHERE p.id = :id")

By using that my Person won't be updated, how should I implement update using hibernate?

解决方案

Two scenarios might pop up for you.

You may want to change a property of the object, and only that property.

If this is the case you want to use the method: find, modify, flush, commit.

em.find(Person.class, person.getId())
person.setStatus("ACTIVE");
em.commit();//implicitly flushes if flush mode is COMMIT or AUTO.

You may want to use the objects properties to update the item.

If this is the case you want to use the method: merge, optionally modify, flush, commit.

em.merge(person);
//modify person if you wish.
em.commit();//implicitly flushes if flush mode is COMMIT or AUTO.

这篇关于Hibernate使用EntityManager进行更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆