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?
personDao.update()is completely unnecessary if everything is run in a single transaction: the state of an entity is automatically made persistent by JPA/Hibernate at the end of the transaction. The getPersonById method could also be reduced toem.find(Person.class, id), which would be simpler, and more efficient, since it wouldn't execute any query if the entity is loaded already.