1

I have a new JPA entity with auto-generated id and I persist it. After that I want to get it again, modify it and persist the changes.

The new entity gets persisted into the database with an auto-generated id but the entity's bookid remains null. This way I cannot use the getBook(id) function to find it again.

@Stateless
public class BookManager implements BookManagerRemote {

    @PersistenceContext
    EntityManager em;

    @EJB
    Authenticator auth;

    public BookManager() {
    }

    @Override
    public void addBook(String user, Konyv konyv) throws InsufficentPrivilegesException {
        if (auth.isAdmin(user)) {
            em.persist(konyv);      
        } else {
            throw new InsufficentPrivilegesException();
        }
    }

@Override
    public Konyv getBook(String user, Integer bookid) throws InsufficentPrivilegesException {
        if (auth.isAdmin(user)) {
            return em.find(Konyv.class, bookid);
        } else {
            throw new InsufficentPrivilegesException();
        }
    }
}

-

Book mistypedBook = new Book("Stanislaw Lem", "Kibeliada");
bookmanager.addBook(name, mistypedBook);

Book whopsBook = bookmanager.getBook(name, mistypedBook.getBookid()/*<-ID IS NULL*/);

How can I sync the newly persisted entity with the database? I've seen JPA Container managed entity update after persist question, but I'm trying to use the entity's id after the method ended. Shouldn't it have the id by then?

Community
  • 1
  • 1
Croo
  • 1,301
  • 2
  • 13
  • 32

1 Answers1

1

Your addBook method needs to return the persisted entity.

em.persist(konyv); 
konyv = em.merge(konyv); 
return konyv;

The entity returned will contain the generated id. As you have the persisted entity back, you won't need to call the getBook method.

JamesB
  • 7,774
  • 2
  • 22
  • 21
  • I'm currently writing tests for the functions, so I have to call getBook method :) I'll try it! – Croo May 25 '13 at 22:00
  • 1
    It worked! It works even without the konyv = em.merge(konyv); line which just amazes me. I don't really get this. I read that persist and merge both puts the entity into "managed" state but I don't understand how can be that another reference to that same object don't work, but returning it does... :S – Croo May 25 '13 at 22:16
  • @Croo The persist method updates the state of the entity passed to it but it doesn't change its reference. When you return it, the updated state is passed back. – JamesB May 25 '13 at 22:30
  • The weird thing is that in my case, the code posted in the question works as expected. That is, after calling addBook, the book contains generated ID. The persistence provider is `EclipseLink`. – jFrenetic May 27 '13 at 20:16