Croo
Croo

Reputation: 1371

Inner workings of JPA

I really don't get it.

If I persist a new item then use it to get the autogenerated key, it fails:

class BookManagerBean {
    @PersistentContext
    EntityManager em;

    @Override
    public void addBook(Book book)  {           
            em.persist(book);                   
    }
}
//...somewhere else
@GetThisObjectByJNDI-OrInject
BookManagerRemote bookManager;    

Book book = new Book("Writer","Title");
bookManager.addBook(book);
book.getBookid() //<--NULL, didn't get synched, but new data with id in DB is fine

But if I return the persisted item, it works:

class BookManagerBean {
    @PersistentContext
    EntityManager em;

    @Override
    public Book addBook(Book book)  {           
            em.persist(book);
            return book;                    
    }
}

//...somewhere else
@GetThisObjectByJNDI-OrInject
BookManagerRemote bookManager;    

Book book = new Book("Writer","Title");
bookManager.book = addBook(book);
book.getBookid() // <--- Auto-generated id is right here! It's synched!

How is this possible?

Upvotes: 3

Views: 150

Answers (1)

James
James

Reputation: 18379

I assume you are accessing BookManagerBean remotely, or as a remote, so the Book it being serialized, so the id is assigned to a different copy, and can only be accessed from the client if you return it.

Either return it, or change you bean to be local, not remote.

Upvotes: 2

Related Questions