EntityManager.persist() doesn't save to database

1k views Asked by At

EntityManager.persist() doesn't save to database with a new entity bean I added to my project. Previously similarly added beans saves to the database.

I have tried adding EntityManager.getTransaction().commit(), which results in an error and EntityManager.flush(), but that results in TransactionRequiredException.

Any help would be appreciated.

3

There are 3 answers

0
Lucas On

Add EntityManager.getTransaction().begin() before persist() and then commit() afterwards.

0
Shoaib Chikate On

All the transactional operation should be kept between begin and commit.

EntityManager.getTransaction().begin()
  .
  .  
  EntityManager.persist();
  EntityManager.flush()
  .
  .
 EntityManager.getTransaction().commit()
0
user2987909 On

Thanks! The begin call was the thing missing here and also I'm using JTA, which means I have to manage it like this:

UserTransaction transaction = (UserTransaction)new InitialContext().lookup("java:comp/UserTransaction");
transaction.begin();
EntityManager em = getEntityManager();
em.persist(YourBean);
transaction.commit();