1

您好,我在 JPA 中自动生成实体的主键时遇到问题。我正在保留实体并尝试从中获取 id 值,但即使我正在刷新它也会返回 null 。我正在使用最新的 glassfish、JPA、netbeans、EJB 3

public class CatchesEntity implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    (...)




    @PersistenceContext(unitName = "DBF")
    private EntityManager em;

    (...)
    public void randomMethod()
    {
         CatchesEntity catchEntity = new CatchesEntity();
         em.persist(catchEntity);
         em.flush();
         System.out.println("CATCH ID: "+catchEntity.getId());

我得到 NULL

4

1 回答 1

2

Calling flush() will send most instructions to the DB, but not the INSERTcommands that are generated on commit(). See this question for more info.

You seem to be working with container-managed transactions, so in general the commit will be performed when the method returns.

If you want to force a commit inside a method, you can disable CMT either on the bean or on the one method and use a UserTransaction:

tx.begin();
...
em.persist();
tx.commit();
于 2013-03-12T12:03:02.623 回答