Hibernate update with EntityManager

Timo picture Timo · Oct 27, 2012 · Viewed 41.1k times · Source

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?

Answer

dseibert picture dseibert · Oct 28, 2012

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.