简体   繁体   中英

How to update entity in JPA

This is my first real exposure to JPA and I'm trying to run the simplest of update statements. I'm running inside a jBoss 7.1.x server using Hibernate as JPA implementation. Any help would be greatly appreciated..

Here is my producer method for EntityManager:

@ApplicationScoped
public class EntityManagerProducer
{

    @PersistenceContext
    private EntityManager entityManager;

    @Produces
    @RequestScoped
    public EntityManager getEntityManager()
    {
        return entityManager;
    }

}

Here is the DAO method that tries to perform the update:

@Inject EntityManager em;

public void updateRequestStatus(String requestNumber, String newStatus)
        {
            em.getTransaction().begin();
            ServiceRequestEntity serviceRequestToUpdate = em.find(RequestEntity.class, requestNumber);
            requestToUpdate.setStatus(newStatus);
            em.merge(serviceRequestToUpdate);
            em.getTransaction().commit();
        }

Here is persistence.xml:

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
 version="2.0">
 <persistence-unit name="database" transaction-type="RESOURCE_LOCAL">
  <jta-data-source>java:/jdbc/myDS</jta-data-source>
  <properties>
   <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" />
   <property name="hibernate.show_sql" value="true" />
   <property name="hibernate.format_sql" value="false" />
   <property name="hibernate.use_sql_comments" value="true" />
  </properties>
 </persistence-unit>
</persistence>

Here is the error message (can provide full stacktrace if needed -it chokes on the "merge" line):

javax.persistence.TransactionRequiredException: JBAS011469: Transaction is required to perform this operation (either use a transaction or extended persistence context)
....
at org.jboss.weld.proxies.EntityManager$-1727851269$Proxy$_$$_WeldClientProxy.merge(EntityManager$-1727851269$Proxy$_$$_WeldClientProxy.java) [weld-core-1.1.5.AS71.Final.jar:]

@Inject annotation on EntityManager I don't think will work. With your current setup I believe you want to inject your EntityManagerProducer class (which is not used in your DAO), and then call your getEntityManager method on it.

The other option would just be to use the @PersistenceContext in your DAO.

You also may want to specify the name of your persistence context as specified in your persistence.xml like: @PersistenceContext(name="database")

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