简体   繁体   中英

Persisting entity to database with JPA and autogenerated primary key identity

I have a full Java EE web application with a presentation layer and a database. I'm using derby with glassfish 3.1 and JPA to handle persistence. I've created a Read ok but now I'm having troulbe doing a Create and persisting to the database. I think I'm close but something is not right with the way I'm trying to do the 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();

}

}

This will be called from another EJB. I also don't want to have to set the ID since that is the primary key I want that generated whenever I call the persist method. The error I get when I test it is:

"Caused by: java.lang.IllegalStateException: Exception Description: Cannot use an EntityTransaction while using JTA."

If you don't know what the problem is with this code but can provide an example of simple persisting with autogenerated primary key that would be just as helpful.

This is my read method that is working:

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 don't need to use Transaction() I haven't found an example online that does not use it for create.

You're using EJB/JTA with transaction-type="JTA" . The container will then manage the transactions itself. You can control the transactions by @TransactionAttribute and @TransactionAttributeType annotations on the EJB class/methods (which by default should however not be necessary). The tutorials which you've read apparently did not use EJB/JTA, but just application managed transactions with transaction-type="RESOURCE_LOCAL" . You should read JPA tutorials which are targeted on use with EJB/JTA.

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

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

by

em.persist(feed);

See also:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM