Reputation: 607
I'm trying to update a row in the database, based on the changes the user made. I passed a Lesson object to my database manager, and now I need to update the object in my database, so that it matches the passed object's properties.
I have the feeling there is a better way than what I'm currently thinking. My guess was to get the object via the id, set all of its properties to the new value, and commit it. But since the id argument is the same as changedLes.getId(), it feels like it would probably be easier way to just overwrite the old DB entry. However I have no idea how to do this and if this is the right way to do it.
void update(ClubLes changedLes, int id) {
try {
GenericDaoJpa.openPersistency();
Clubles les = em.find(ClubLes.class, id);
em.getTransaction().begin();
//setters? eg les.setName(changedLes.getName())
em.getTransaction().commit();
GenericDaoJpa.closePersistency();
} catch (NoResultException e) {
GenericDaoJpa.closePersistency();
throw new NoResultException("Les could not be modified! try again!");
}
}
I'm using auto generated keys, so I'm not sure if that will cause a problem.
Upvotes: 1
Views: 1686
Reputation: 1014
To update an entity you need to do
em.merge(entity);
em.flush();
See
https://docs.oracle.com/javaee/7/api/javax/persistence/EntityManager.html#merge-T-
https://docs.oracle.com/javaee/7/api/javax/persistence/EntityManager.html#flush--
Upvotes: 2