JPA的内部运作

时间:2013-05-25 22:31:34

标签: java jpa entity java-ee-6 ejb-3.1

我真的不明白。

如果我坚持使用新项目然后使用它获取自动生成的密钥,则会失败:

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

但是,如果我返回持久项目,它会起作用:

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!

这怎么可能?

1 个答案:

答案 0 :(得分:2)

我假设您正在远程访问BookManagerBean,或者作为远程访问,因此将其序列化为Book,因此将id分配给不同的副本,并且只有在您返回时才能从客户端访问。

要么返回它,要么将bean更改为本地,而不是远程。