1

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.

iCV
  • 547
  • 1
  • 8
  • 29

1 Answers1

2

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--

admlz635
  • 1,001
  • 1
  • 9
  • 18
  • Will this take care of the existing entity? Or do I need to do something else aswell – iCV May 03 '19 at 18:13
  • It will check the id to update an entity, if the entity does not exists it will create a new instance, See https://stackoverflow.com/questions/1069992/jpa-entitymanager-why-use-persist-over-merge – admlz635 May 03 '19 at 18:31