1 Reply Latest reply: Feb 21, 2012 10:04 AM by cdelahun RSS

    JPA merge not working

    917976
      Hi all

      I am new in JPA and trying to create a simple entity. I am using Oracle 10 xe database and JDeveloper IDE and integrated weblogic server 10. My steps are as follows,

      1. Create Entity from Table
      2. Create Java Service Facade and test entity. Here merge is working.
      3. Create Stateless Session bean
      4. Create web service and call the session bean from web service.
      5. Test web service. Here Merge not working and did not throw any exception.

      Its urgent and Please help me. Otherwise I have to back in plain jdbc. Thanks in advance. My source code is added.

      ---
      Mehrab


      1. Entity Class
      --------------------------------------------------------------------------------------------------------------------------------------------------------
      package model.entity;

      import java.io.Serializable;

      import java.sql.Timestamp;

      import java.util.Date;

      import javax.persistence.Column;
      import javax.persistence.Entity;
      import javax.persistence.GeneratedValue;
      import javax.persistence.GenerationType;
      import javax.persistence.Id;
      import javax.persistence.NamedQueries;
      import javax.persistence.NamedQuery;
      import javax.persistence.SequenceGenerator;
      import javax.persistence.Table;
      import javax.persistence.Temporal;
      import javax.persistence.TemporalType;

      @Entity
      @NamedQueries({
      @NamedQuery(name = "MbrLevel.findAll", query = "select o from MbrLevel o"),
      @NamedQuery(name = "MbrLevel.byName", query = "select o from MbrLevel o where upper(o.name) like upper(:name)"),
      @NamedQuery(name = "MbrLevel.byLevelCode", query = "select o from MbrLevel o where upper(o.mbrLevelCode) like upper(:mbrLevelCode)")
      })
      @Table(name = "MBR_LEVEL")
      @SequenceGenerator(name = "MBR_LEVEL_SEQ",schema = "HR",initialValue = 1,allocationSize = 1)
      public class MbrLevel implements Serializable {
      @Column(name="AUD_CREATED_BY", nullable = false)
      private Long audCreatedBy;
      @Column(name="AUD_CREATED_DTTM", nullable = false)
      @Temporal(value = TemporalType.TIMESTAMP)
      private Date audCreatedDttm;
      @Column(name="AUD_UPDATED_BY")
      private Long audUpdatedBy;
      @Column(name="AUD_UPDATED_DTTM")
      @Temporal(value = TemporalType.TIMESTAMP)
      private Date audUpdatedDttm;
      @Column(name="MBR_LEVEL_CODE", nullable = false, length = 10)
      private String mbrLevelCode;
      @Id
      @GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "MBR_LEVEL_SEQ")
      @Column(name="MBR_LEVEL_ID", nullable = false)
      private Long mbrLevelId;
      @Column(nullable = false, length = 180)
      private String name;
      @Column(name="SHORT_NAME", nullable = false, length = 20)
      private String shortName;

      public MbrLevel() {
      }

      public MbrLevel(Long audCreatedBy, Date audCreatedDttm,
      Long audUpdatedBy, Date audUpdatedDttm,
      String mbrLevelCode, Long mbrLevelId, String name,
      String shortName) {
      this.audCreatedBy = audCreatedBy;
      this.audCreatedDttm = audCreatedDttm;
      this.audUpdatedBy = audUpdatedBy;
      this.audUpdatedDttm = audUpdatedDttm;
      this.mbrLevelCode = mbrLevelCode;
      this.mbrLevelId = mbrLevelId;
      this.name = name;
      this.shortName = shortName;
      }

      public Long getAudCreatedBy() {
      return audCreatedBy;
      }

      public void setAudCreatedBy(Long audCreatedBy) {
      this.audCreatedBy = audCreatedBy;
      }

      public Date getAudCreatedDttm() {
      return audCreatedDttm;
      }

      public void setAudCreatedDttm(Date audCreatedDttm) {
      this.audCreatedDttm = audCreatedDttm;
      }

      public Long getAudUpdatedBy() {
      return audUpdatedBy;
      }

      public void setAudUpdatedBy(Long audUpdatedBy) {
      this.audUpdatedBy = audUpdatedBy;
      }

      public Date getAudUpdatedDttm() {
      return audUpdatedDttm;
      }

      public void setAudUpdatedDttm(Date audUpdatedDttm) {
      this.audUpdatedDttm = audUpdatedDttm;
      }

      public String getMbrLevelCode() {
      return mbrLevelCode;
      }

      public void setMbrLevelCode(String mbrLevelCode) {
      this.mbrLevelCode = mbrLevelCode;
      }

      public Long getMbrLevelId() {
      return mbrLevelId;
      }

      public void setMbrLevelId(Long mbrLevelId) {
      this.mbrLevelId = mbrLevelId;
      }

      public String getName() {
      return name;
      }

      public void setName(String name) {
      this.name = name;
      }

      public String getShortName() {
      return shortName;
      }

      public void setShortName(String shortName) {
      this.shortName = shortName;
      }


      @Override
      public boolean equals(Object object) {
      if (this == object) {
      return true;
      }
      if (!(object instanceof MbrLevel)) {
      return false;
      }
      final MbrLevel other = (MbrLevel)object;
      if (!(mbrLevelId == null ? other.mbrLevelId == null : mbrLevelId.equals(other.mbrLevelId))) {
      return false;
      }
      return true;
      }

      @Override
      public int hashCode() {
      final int PRIME = 37;
      int result = 1;
      result = PRIME * result + ((mbrLevelId == null) ? 0 : mbrLevelId.hashCode());
      return result;
      }
      }


      2. Java Service Facade class
      ----------------------------------------------------------------------------------------------------------------------------------------------------------------

      package mode.ejbl;

      import java.sql.Timestamp;

      import java.util.Date;
      import java.util.List;

      import javax.persistence.EntityManager;
      import javax.persistence.EntityManagerFactory;
      import javax.persistence.EntityTransaction;
      import javax.persistence.Persistence;
      import javax.persistence.Query;

      import model.entity.MbrLevel;

      public class JavaServiceFacade {
      private EntityManagerFactory emf = Persistence.createEntityManagerFactory("ModelPU");

      public JavaServiceFacade() {
      }

      public static void main(String [] args) {
      try{
      final JavaServiceFacade javaServiceFacade = new JavaServiceFacade();
      // MbrLevel m = javaServiceFacade.getEntityManager().find(MbrLevel.class, (6L));
      MbrLevel m = new MbrLevel();
      // m.setMbrLevelId(1L);
      m.setMbrLevelCode("mbrcode6");
      m.setName("mbrname6");
      m.setShortName("sm6");
      m.setAudCreatedBy(5L);
      // m.setAudCreatedDttm(new Timestamp(new Date().getTime()));
      m.setAudCreatedDttm(new Date());
      m.setAudUpdatedBy(3L);
      m.setAudUpdatedDttm(new Date());
      // javaServiceFacade.persistMbrLevel(m);
      javaServiceFacade.mergeMbrLevel(m);
      }catch(Exception e){
      e.printStackTrace();
      }
      }

      private EntityManager getEntityManager() {
      return emf.createEntityManager();
      }

      public Object queryByRange(String jpqlStmt, int firstResult,
      int maxResults) {
      Query query = getEntityManager().createQuery(jpqlStmt);
      if (firstResult > 0) {
      query = query.setFirstResult(firstResult);
      }
      if (maxResults > 0) {
      query = query.setMaxResults(maxResults);
      }
      return query.getResultList();
      }

      private Object _persistEntity(Object entity) {
      final EntityManager em = getEntityManager();
      try {
      final EntityTransaction et = em.getTransaction();
      try {
      et.begin();
      em.persist(entity);
      et.commit();
      } finally {
      if (et != null && et.isActive()) {
      entity = null;
      et.rollback();
      }
      }
      } finally {
      if (em != null && em.isOpen()) {
      em.close();
      }
      }
      return entity;
      }

      public MbrLevel persistMbrLevel(MbrLevel mbrLevel) {
      return (MbrLevel)_persistEntity(mbrLevel);
      }

      private Object _mergeEntity(Object entity) {
      final EntityManager em = getEntityManager();
      try {
      final EntityTransaction et = em.getTransaction();
      try {
      et.begin();
      em.merge(entity);
      et.commit();
      } finally {
      if (et != null && et.isActive()) {
      entity = null;
      et.rollback();
      }
      }
      } finally {
      if (em != null && em.isOpen()) {
      em.close();
      }
      }
      return entity;
      }

      public MbrLevel mergeMbrLevel(MbrLevel mbrLevel) {
      return (MbrLevel)_mergeEntity(mbrLevel);
      }

      public void removeMbrLevel(MbrLevel mbrLevel) {
      final EntityManager em = getEntityManager();
      try {
      final EntityTransaction et = em.getTransaction();
      try {
      et.begin();
      mbrLevel = em.find(MbrLevel.class, mbrLevel.getMbrLevelId());
      em.remove(mbrLevel);
      et.commit();
      } finally {
      if (et != null && et.isActive()) {
      et.rollback();
      }
      }
      } finally {
      if (em != null && em.isOpen()) {
      em.close();
      }
      }
      }

      /** <code>select o from MbrLevel o</code> */
      public List<MbrLevel> getMbrLevelFindAll() {
      return getEntityManager().createNamedQuery("MbrLevel.findAll").getResultList();
      }
      }



      3. Stateless Session bean
      ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

      package model.ejb;

      import java.util.List;

      import javax.ejb.Stateful;
      import javax.ejb.Stateless;

      import javax.persistence.EntityManager;
      import javax.persistence.PersistenceContext;
      import javax.persistence.Query;

      import model.entity.MbrLevel;

      @Stateless(name = "MbrLevelSessionEJB", mappedName = "MbrLevelApp-Model-MbrLevelSessionEJB")
      public class MbrLevelSessionEJBBean implements MbrLevelSessionEJB,
      MbrLevelSessionEJBLocal {
      @PersistenceContext(unitName="ModelPU")
      private EntityManager em;

      public MbrLevelSessionEJBBean() {
      }

      public Object queryByRange(String jpqlStmt, int firstResult,
      int maxResults) {
      Query query = em.createQuery(jpqlStmt);
      if (firstResult > 0) {
      query = query.setFirstResult(firstResult);
      }
      if (maxResults > 0) {
      query = query.setMaxResults(maxResults);
      }
      return query.getResultList();
      }


      public MbrLevel persistMbrLevel(MbrLevel mbrLevel) {
      em.persist(mbrLevel);
      return mbrLevel;
      }


      public MbrLevel mergeMbrLevel(MbrLevel mbrLevel) {
      return em.merge(mbrLevel);
      }


      public void removeMbrLevel(MbrLevel mbrLevel) {
      mbrLevel = em.find(MbrLevel.class, mbrLevel.getMbrLevelId());
      em.remove(mbrLevel);
      }

      /** <code>select o from MbrLevel o</code> */

      public List<MbrLevel> getMbrLevelFindAll() {
      return em.createNamedQuery("MbrLevel.findAll").getResultList();
      }

      /** <code>select o from MbrLevel o where upper(o.name) like upper(:name)</code> */

      public List<MbrLevel> getMbrLevelByName(String name) {
      return em.createNamedQuery("MbrLevel.byName").setParameter("name", name).getResultList();
      }

      /** <code>select o from MbrLevel o where upper(o.mbrLevelCode) like upper(:mbrLevelCode)</code> */

      public List<MbrLevel> getMbrLevelByLevelCode(String mbrLevelCode) {
      return em.createNamedQuery("MbrLevel.byLevelCode").setParameter("mbrLevelCode", mbrLevelCode).getResultList();
      }
      }


      4. Web service class
      -----------------------------------------------------------------------------------------------------------------------------------------------------------

      package model.ejb.service;

      import javax.ejb.EJB;

      import javax.jws.WebMethod;

      import javax.jws.WebParam;
      import javax.jws.WebService;

      import javax.xml.ws.BindingType;
      import javax.xml.ws.soap.SOAPBinding;

      import model.ejb.MbrLevelSessionEJB;

      import model.ejb.MbrLevelSessionEJBBean;

      import model.ejb.MbrLevelSessionEJBLocal;

      import model.entity.MbrLevel;

      @WebService(serviceName = "MbrLevelService", portName = "MbrLevelServiceSoap12HttpPort")
      @BindingType(SOAPBinding.SOAP12HTTP_BINDING)
      public class MbrLevelService {

      @EJB
      private MbrLevelSessionEJB ejb;


      public MbrLevel mergeMbrLevel(MbrLevel mbrLevel){
      return ejb.mergeMbrLevel(mbrLevel);
      }
      }


      5. Persistance.xml
      ---------------------------------------------------------------------------------------------------------------------------------------------------------

      <?xml version="1.0" encoding="windows-1252" ?>
      <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_1_0.xsd"
      version="1.0">
      <persistence-unit name="ModelPU" transaction-type="RESOURCE_LOCAL">
      <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
      <!-- jta-data-source>java:/app/jdbc/jdbc/HRConnDS</jta-data-source -->
      <class>model.entity.MbrLevel</class>
      <properties>
      <property name="eclipselink.jdbc.driver"
      value="oracle.jdbc.OracleDriver"/>
      <property name="eclipselink.jdbc.url"
      value="jdbc:oracle:thin:@localhost:1521:XE"/>
      <property name="eclipselink.jdbc.user" value="hr"/>
      <property name="eclipselink.jdbc.password"
      value="62C32F70E98297522AD97E15439FAC0E"/>
      <property name="eclipselink.logging.level" value="FINER"/>
      <property name="eclipselink.target-server" value="WebLogic_10"/>
      <property name="eclipselink.jdbc.native-sql" value="true"/>
      <!-- property name="eclipselink.ddl-generation" value="create-tables"/ -->
      <!--property name="javax.persistence.jtaDataSource"
      value="java:/app/jdbc/jdbc/HRConnDS"/-->
      <property name="eclipselink.persistence-context.flush-mode"
      value="COMMIT"/>
      <property name="eclipselink.flush-clear.cache" value="Merge"/>
      </properties>
      </persistence-unit>
      <persistence-unit name="Model">
      <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
      <jta-data-source>java:/app/jdbc/jdbc/HRConnDS</jta-data-source>
      <class>model.entity.MbrLevel</class>
      <properties>
      <property name="eclipselink.target-server" value="WebLogic_10"/>
      <property name="javax.persistence.jtaDataSource"
      value="java:/app/jdbc/jdbc/HRConnDS"/>
      </properties>
      </persistence-unit>
      </persistence>


      6. web.xml
      ---------------------------------------------------------------------------------------------------------------

      <?xml version = '1.0' encoding = 'windows-1252'?>
      <web-app xmlns="http://java.sun.com/xml/ns/javaee"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
      <filter>
      <filter-name>JpsFilter</filter-name>
      <filter-class>oracle.security.jps.ee.http.JpsFilter</filter-class>
      <init-param>
      <param-name>enable.anonymous</param-name>
      <param-value>true</param-value>
      </init-param>
      </filter>
      <filter-mapping>
      <filter-name>JpsFilter</filter-name>
      <url-pattern>/*</url-pattern>
      <dispatcher>FORWARD</dispatcher>
      <dispatcher>REQUEST</dispatcher>
      <dispatcher>INCLUDE</dispatcher>
      </filter-mapping>
      <servlet>
      <servlet-name>MbrLevelServiceSoap12HttpPort</servlet-name>
      <servlet-class>model.ejb.service.MbrLevelService</servlet-class>
      <load-on-startup>1</load-on-startup>
      </servlet>
      <servlet-mapping>
      <servlet-name>MbrLevelServiceSoap12HttpPort</servlet-name>
      <url-pattern>/MbrLevelServiceSoap12HttpPort</url-pattern>
      </servlet-mapping>
      </web-app>
        • 1. Re: JPA merge not working
          cdelahun
          There are some problems with how you are attempting to run it. In the working case, the ModelPU is set to resource_local and your JavaServiceFacade starts and commits transactions manually as required. In the non-working case, you seem to be injecting the exact same resource_local persistence context, but not starting/commiting transactions - this is why you do not see updates.

          You probably want to be using a JTA context type and the jta-data-source for use with your MbrLevelSessionEJBBean, and you will need to be sure to wrap the appropriate methods within transactions. If not, you will need to change your MbrLevelSessionEJBBean to operate the same as the JavaServiceFacade.

          Check http://wiki.eclipse.org/EclipseLink/Examples/JPA for general application server examples and http://wiki.eclipse.org/EclipseLink/Examples/JPA/WebLogic_Web_Tutorial for weblogic specific ones if you want to go the JTA route.


          Best Regards,
          Chris