The ID is only guaranteed to be generated at flush time. Persisting an entity only makes it "attached" to the persistence context. So, either flush the entity manager explicitely:
em.persist(abc);
em.flush();
return abc.getId();
or return the entity itself rather than its ID. When the transaction ends, the flush will happen, and users of the entity outside of the transaction will thus see the generated ID in the entity.
@Override
public ABC addNewABC(ABC abc) {
abcDao.insertABC(abc);
return abc;
}
@Entity
public class ABC implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
}
check that @GeneratedValue notation is there in your entity class.This tells JPA about your entity property auto-generated behavior
This is how I did it:
EntityManager entityManager = getEntityManager();
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
entityManager.persist(object);
transaction.commit();
long id = object.getId();
entityManager.close();
You could also use GenerationType.TABLE instead of IDENTITY which is only available after the insert.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With