1

Hello I am having problem with auto generated primary key of entity in JPA. I am persisting the entity and trying to get the id value out of it, but it returns null even though I am doing flush. I am using latest 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());

I get NULL

Taks
  • 2,033
  • 4
  • 18
  • 23

1 Answers1

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();
Community
  • 1
  • 1
kostja
  • 60,521
  • 48
  • 179
  • 224