Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate update with EntityManager

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?

like image 567
Timo Avatar asked Oct 27 '12 18:10

Timo


1 Answers

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.
like image 171
dseibert Avatar answered Sep 29 '22 14:09

dseibert