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