Storing an entity in a database using JPA and a self-generated primary key identifier

I have a complete Java EE web application with presentation layer and database. I use 3.1 chip glass derby and JPA to handle the stubbornness. I created a “Read” message, but now I have a troulbe doing Create and saved to the database. I think I'm close, but something is wrong with the way I'm trying to create.

Here is my EAO code:

/** * Session Bean implementation class XRSSeao */ @Stateless @LocalBean public class XRSSeao { @PersistenceContext EntityManager em; public XRSSeao() {} public void addEvent(String update){ Feed feed = new Feed(); feed.setStatus(update); feed.setId(2); em.getTransaction().begin(); em.persist(feed); em.flush(); em.clear(); em.getTransaction().commit(); } } 

It will be called from another EJB. I also do not want to set the identifier, since this is the primary key that I want to create when I call the persist method. The error I get when I check:

"Caused by: java.lang.IllegalStateException: Exception Description: EntityTransaction cannot be used when using JTA.

If you don’t know what the problem is with this code, but you can provide an example of a simple save with an auto-generated primary key that would be just as useful.

This is my reading method that works:

 public String lastUpdate(){ String resultString; Query q = em.createQuery("SELECT x FROM Feed x WHERE x.id = 1"); List<Feed> ListofStatus = q.getResultList(); //alternatively you can use getResultList() for non 1 object is expected. Feed returnStatusObject = ListofStatus.get(0); resultString = returnStatusObject.getStatus(); return resultString; 

}

If I do not need to use Transaction (), I have not found an example on the Internet that does not use it to create.

0
java java-ee jpa persistence jpql
source share
1 answer

You are using EJB / JTA with transaction-type="JTA" . Then the container will manage the transactions themselves. You can control the transactions @TransactionAttribute and @TransactionAttributeType annotations for the EJB class / methods (which by default, however, will not be needed). The tutorials you read did not seem to use EJB / JTA, but simply controlled applications with transaction-type="RESOURCE_LOCAL" . You should read JPA tutorials intended for use with EJB / JTA.

To fix your problem, I assume that you want to continue using EJB / JTA-, replace

 em.getTransaction().begin(); em.persist(feed); em.flush(); em.clear(); em.getTransaction().commit(); 

by

 em.persist(feed); 

See also:

+1
source share

All Articles