Domanda

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?

È stato utile?

Soluzione

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.

Altri suggerimenti

Hibernate and also other JPA implementations automatically manage state of entities and save it to database if modification is enclosed in transaction. You do not need to explicitly call merge or update methods.

If you are using resource-local transactions (not managed by JTA transaction manager) try something like this:

EntityTransaction tx = entityManager.getTransaction();
tx.begin();
Person person = personDao.getPersonById(1);
person.setAge(23);
person.setLastname("McName");
tx.commit();

and all your modifications will be automatically saved in database.

If you are using JTA then you have to mark the transaction boundaries in some other way, for example by using Spring AOP @Transactional annotation.

I don't know what you're asking exactly, but in your method, Person.getPersonById(int id), you can simplify your code with the following:

return entityManager.find(Person.class, id);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top