Hi,

The Java Persistence Architecture API (JPA) is a Java specification for accessing, persisting, and managing data between Java objects / classes and a relational database. JPA was defined as part of the EJB 3.0 specification as a replacement for the EJB 2 CMP Entity Beans specification. JPA is now considered the standard industry approach for Object to Relational Mapping (ORM) in the Java Industry.

The JBoss Application Server JPA subsystem implements the JPA 2.0 container-managed requirements. JPA Applications use the Hibernate (core) 4.0 persistence provider, that is included with JBoss AS. Hibernate 4 is packaged with the AS and is the default persistence provider. The JPA 2.0 Specifications can be found in the following link: http://jcp.org/aboutJava/communityprocess/pfd/jsr317/index.html

A Best reference for JPA features inside JBoss AS7 can be foun in the following link: https://docs.jboss.org/author/display/AS7/JPA+Reference+Guide

However in this current Demo we will just create a Simple JPA persistence unit With the help of “Oracle TopLink 12c (12.1.1)” and then we will try to insert some employee detils insie the DataBase. So basically this is just as a startup.

In this example we will mainly focus on following points

Point-1). We will see how to use “Oracle TopLink 12c (12.1.1)” with JBossAS7.1.1.Final.

Point-2). For Web Applications we should put the “persistence.xml” file inside “${WEB_APPLICATION}/WEB-INF/classes/META-INF/persistence.xml” AND For EJB Applications we should put the “persistence.xml” file inside “${EJB_JAR}/META-INF”

Point-3). To inject the EntityManager inside our Web Components we can use the annotation @javax.persistence.PersistenceContext(unitName=”name”)

Point-4). We can use the @javax.ejb.EJB annotation to inject an Enterprise Java Bean inside our app components. Like @EJB(lookup=”jndiName”)

Point-5). We will see what error we get when we dont define following property in our “persistence.xml” file while using Oracle topLink. < property name=”jboss.as.jpa.providerModule” value=”org.eclipse.persistence.jpa” />

Point-6). The Full Demo can be downloaded from the following Github repository:
https://github.com/jaysensharma/MiddlewareMagicDemos/tree/master/JPA2_And_Toplink_On_AS7

Creating DataSource On JBossAS7

Step-1). Here we are using JBoss AS7 latest build “jboss-as-7.1.1.Final” which can be downloaded from the following link: http://www.jboss.org/jbossas/downloads

Step-2). In order to get more details on how to create MySQL DataSource in JBoss AS7 you can refer to the following article: http://middlewaremagic.com/jboss/?p=872
Just place the “mysql-connector-java-5.1.13-bin.jar” MySQL Jdbc driver in your JBoss Deployments directory, Then create a DataSource inside “${JBOSS_HOME}/standalone/configuration/standalone-full.xml” file as following:

        <subsystem xmlns="urn:jboss:domain:datasources:1.0">
            <datasources>

                <!-- Below is the DataSource Configuration which we added for our JPA TestCase-->
                <datasource jta="false" jndi-name="java:/MySqlDS" pool-name="MySqlDS_Pool" enabled="true" use-ccm="false">
                    <connection-url>jdbc:mysql://localhost:3306/testDB</connection-url>
                    <driver-class>com.mysql.jdbc.Driver</driver-class>
                    <driver>mysql-connector-java-5.1.13-bin.jar</driver>
                    <security>
                        <user-name>someDBUserName</user-name>
                        <password>someDBPassword</password>
                    </security>
                </datasource>
                <drivers>
                    <driver name="h2" module="com.h2database.h2">
                        <xa-datasource-class>org.h2.jdbcx.JdbcDataSource</xa-datasource-class>
                    </driver>
                </drivers>
            </datasources>
        </subsystem>

Creating Oracle Toplink Module In JBossAS7

Step-3). Download the “Oracle TopLink 12c (12.1.1)” toplink.zip (25,456,648 bytes) from the following link:
http://www.oracle.com/technetwork/middleware/toplink/downloads/index.html

Step-4). Extract the downloaded “toplink.zip” and then copy the two Jars placed insie the extracted “toplink/jlib” directory. The Jar names will be “toplink-grid.jar” And “eclipselink.jar”

Step-5). Create the following directory structure [jboss-as-7.1.1.Final/modules/org/eclipse/persistence/jpa/main] in your file system so that the Oracle TopLink Module can be created.

     .
     .  
     jboss-as-7.1.1.Final/modules/
     │  
     ├──org
     │   │       
     │   ├── eclipse
     │   │   └── persistence
     │   │       └── jpa
     │   │           └── main
     │   │               ├── eclipselink.jar
     │   │               ├
     │   │               ├── toplink-grid.jar
     │   │               ├
     │   │               ├── module.xml
     .
     .

Paste the “toplink-grid.jar” And “eclipselink.jar” from downloaded toplink s/w into the “jboss-as-7.1.1.Final/modules/org/eclipse/persistence/jpa/main” and then write the following kind of “module.xml” file:

<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.1" name="org.eclipse.persistence.jpa">
    <resources>
        <resource-root path="eclipselink.jar"/>
        <resource-root path="toplink-grid.jar"/>
    </resources>

        <dependencies> 
            <module name="javax.persistence.api"/> 
            <module name="javax.transaction.api"/> 
            <module name="javax.validation.api"/> 
        </dependencies> 
</module>

Step-6). Restart your JBoss AS7 from inside “/home/userone/jboss-as-7.1.1.Final/bin” directory as following:

.
 ./standalone.sh -c standalone-full.xml
.

Developing Oracle Toplink JPA Demo

Step1). Create a directory somewhere in your filesystem like “/home/userone/JPA2_And_Toplink_On_AS7” where we will place our application build related stuff. Then create another directory “src” inside “/home/userone/JPA2_And_Toplink_On_AS7” where we will be placing our source codes and JSPs.

Step2). Now first of all we will create an Entity “Employee.java” as following inside the “/home/userone/JPA2_And_Toplink_On_AS7/src” directory.

package jpa;
import java.io.Serializable;
import javax.persistence.*;
import java.lang.Integer;

@Entity
@Table(name="Employee")
public class Employee implements Serializable {
	private static final long serialVersionUID = 1L;

	@Id
	private Integer empno;

	private String ename;

    public Employee() {
    	System.out.println("Employee Object Created. this: "+this);
    }

	public Integer getEmpno() {
		return this.empno;
	}

	public void setEmpno(Integer empno) {
		this.empno = empno;
	}

	public String getEname() {
		return this.ename;
	}

	public void setEname(String ename) {
		this.ename = ename;
	}

}

Step3). Now we will create a Simple Stateless SessionBean remote Interface “EmployeeServiceRemote.java” inside “/home/userone/JPA2_And_Toplink_On_AS7/src” directory as following:

package jpa;
import java.lang.Integer;
import java.util.Collection;
import javax.ejb.Remote;
@Remote

public interface EmployeeServiceRemote{
  public void doAction();
  public Employee createEmployee(Integer id, String name);
  public void removeEmployee(Integer id);
  public Employee findEmployee(Integer id);
  public Collection<Employee> findAllEmployees() ;

}

Step4). Now we will Stateless Session Bean class “EmployeeService.java” by implementing the interface “EmployeeServiceRemote.java”. Place this file as well inside the “/home/userone/JPA2_And_Toplink_On_AS7/src” directory as following:

package jpa;
import java.lang.Integer;
import java.util.Collection;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import javax.persistence.EntityTransaction;
import javax.ejb.*;

@Stateless
public class EmployeeService implements EmployeeServiceRemote {
  @PersistenceContext(unitName="EmployeeService")
  EntityManager em;

  public EmployeeService() {
	  System.out.println("ntEmployeeService  Object Created. this: "+this);
  }

  @TransactionAttribute (TransactionAttributeType.REQUIRED)
  public Employee createEmployee(Integer id, String name) {
    Employee emp = new Employee();
    emp.setEmpno(id);
    emp.setEname(name);
    System.out.println("nt[EmployeeService] Before em.persist(emp)");

    try{ 
         em.getTransaction().begin();
         em.persist(emp);
         em.flush();
         em.getTransaction().commit();
       } 
    catch(Exception e)
       {
          e.printStackTrace();
          try{   em.getTransaction().rollback();   } catch(Exception ee)  {  ee.printStackTrace();  }
       }

    System.out.println("nt[EmployeeService] Before findEmployee(id)");
    emp = findEmployee(id);
    System.out.println("nt[EmployeeService] Inside createEmployee() findEmployee result: "+emp);
    return emp;
  }

  public void removeEmployee(Integer id) {
	System.out.println("nt Inside removeEmployee("+id+")");
    Employee emp = findEmployee(id);
    if (emp != null) {
       try{ 
            em.getTransaction().begin();
            em.remove(emp);
            em.getTransaction().commit();
          } 
       catch(Exception e)
          {
             e.printStackTrace();
             try{   em.getTransaction().rollback();   } catch(Exception ee)  {  ee.printStackTrace();  }
          }
    }
  }

  public Employee findEmployee(Integer id) {
	System.out.println("nt Inside findEmployee("+id+")");
    return em.find(Employee.class, id);
  }

  @SuppressWarnings("unchecked")
  public Collection<Employee> findAllEmployees() {
	System.out.println("nt Inside findAllEmployees()");
    Query query = em.createQuery("SELECT e FROM Employee e");
    return (Collection<Employee>) query.getResultList();
  }

  public void doAction(){
  }
}


Step5). Now we will write the “persistence.xml” file inside the “/home/userone/JPA2_And_Toplink_On_AS7/src” directory as following:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
	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">
  <persistence-unit name="EmployeeService">
       <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
       <jta-data-source>java:/MySqlDS</jta-data-source> 
       <class>jpa.Employee</class>

       <properties>
          <!-- Note jboss.as.jpa.providerModule property is very important -->
          <property name="jboss.as.jpa.providerModule" value="org.eclipse.persistence.jpa" />
       </properties>
  </persistence-unit>
</persistence>

NOTE: We need to make sure that this “persistence.xml” file goes inside the “${war.name}/WEB-INF/classes/META-INF” directory of our WAR file. Note jboss.as.jpa.providerModule property is very important

Step6). Now we will write a simple “index.jsp” page to just provide a some input forms so that a user can enter the employee name and id details , Place this file as well inside the “/home/userone/JPA2_And_Toplink_On_AS7/src” directory as following:

<html>
<head>
<title>JPA Demo In JBoss AS7</title>
</head>
<body>
   <form action="TestServlet">
   Enter Employee ID : <input name="empId" type="text" value="" /> <BR/>
   Enter Employee Name : <input name="empName" type="text" value="" /> <BR/>
   <input type="submit" value="Store" />
   </form>
</body>
</html>

Step7). We will write the “TestServlet.java” inside the “/home/userone/JPA2_And_Toplink_On_AS7/src” as following in order to insert the details entered by the user in previous index.jsp page.

package servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.Integer;
import javax.ejb.EJB;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.transaction.*;
import javax.annotation.*;
import jpa.Employee;

@WebServlet(value="/TestServlet")
public class TestServlet extends HttpServlet 
  {
	private static final long serialVersionUID = 1L;


        @Resource private UserTransaction 
        utx;
 
        @PersistenceContext(unitName="EmployeeService")
	EntityManager em;
	  
        @EJB(lookup="java:global/JPA_BASIC_Demo/EmployeeService!jpa.EmployeeServiceRemote")
        jpa.EmployeeServiceRemote remote;


	public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                PrintWriter out=null;
		try {
			System.out.println("inside TestServlet service()");
			System.out.println("GOT the UserTransaction       :  "+utx);
			System.out.println("Got jpa.EmployeeServiceRemote :  "+remote);
			out=response.getWriter();			
			
                        remote.createEmployee(new Integer(request.getParameter("empId")),request.getParameter("empName"));

                        out.println("<html><head><title>JPA Insert</title></head><body>");
			out.println("<BR>Employee Record Inserted in the Database.<BR>");
                        out.println("<TABLE border="10%">");
                        out.println("<TR><TD>EmpID</TD><TD>EmpName</TD></TR>");
			for(Employee tmp:remote.findAllEmployees())
			{
			   out.println("<TR><TD>"+tmp.getEmpno()+"</TD><TD>"+tmp.getEname()+"</TD></TR>");
			}
                        out.println("</TABLE>");
                        out.println("<BR><BR><a href="index.jsp"> Want to insert Some More Employee Records ?</a></body></html>");
		     } 
                 catch (Exception e) 
                     {
			e.printStackTrace();
		     }
	}
}

Step8). As we created a module “org.eclipse.persistence.jpa” earlier which we are going to use in our web application. So we will need to create a “jboss-deployment-structure.xml” file as following:

<?xml version="1.0" encoding="UTF-8"?>
<jboss-deployment-structure>
  <deployment>
    <dependencies>
      <module name="org.eclipse.persistence.jpa" />
    </dependencies>
  </deployment>
</jboss-deployment-structure>

NOTE: Once our application is build then we should be able to see this file present inside our WebApplication “WEB-INF/jboss-deployment-structure.xml”.

Step9). Now the most important part, here we are going to develop “build.xml” ANT file, which will build, deploy our web application on the JBoss AS7.1 Beta Server, so write the following “build.xml” file inside “/home/userone/JPA2_And_Toplink_On_AS7” directory.

<project name="JPA_BASIC_Demo" default="deploy">
<property name="jboss.home" value="/NotBackedUp/JBoss_All/jboss-as-7.1.1.Final" />
<property name="jboss.module.dir" value="${jboss.home}/modules" />
<property name="basedir" value="." />
<property name="tmp.dir" value="tmp" />
<property name="output.dir" value="build" />
<property name="src.dir" value="src" />
<property name="war.name" value="JPA_BASIC_Demo.war" />
 
   <path id="jboss.classpath">
     <fileset dir="${jboss.module.dir}">
        <include name="**/*.jar"/>
     </fileset>
   </path>
 
        <target name="init">
           <delete dir="${output.dir}" />
           <mkdir dir="${output.dir}" />
           <delete dir="${tmp.dir}" />
           <mkdir dir="${tmp.dir}" />
           <mkdir dir="${tmp.dir}/WEB-INF/classes/META-INF"/>
        </target>
 
        <target name="build" depends="init">
           <javac srcdir="${src.dir}" destdir="${tmp.dir}/WEB-INF/classes"  includes="*.java" classpathref="jboss.classpath" />
           <copy todir="${tmp.dir}/WEB-INF/classes">
                <fileset dir="${src.dir}" includes="**/*.java"/>
           </copy>
           <copy file="${src.dir}/index.jsp" tofile="${tmp.dir}/index.jsp"/>
           <copy file="${src.dir}/jboss-deployment-structure.xml" tofile="${tmp.dir}/WEB-INF/jboss-deployment-structure.xml"/>

           <!-- Make Sure that the persistence.xml file is placed inside "${war.name}/WEB-INF/classes/META-INF" directory -->
           <copy file="${src.dir}/persistence.xml" tofile="${tmp.dir}/WEB-INF/classes/META-INF/persistence.xml"/>

           <jar jarfile="${tmp.dir}/${war.name}" basedir="${tmp.dir}" compress="true" />
           <copy file="${tmp.dir}/${war.name}" tofile="${output.dir}/${war.name}"/>

           <delete includeEmptyDirs="true">
              <fileset dir="${tmp.dir}"/>
           </delete>
        </target>
 
        <target name="deploy" depends="build">
            <echo message="*******************  Deploying the WAR file ${war.name} *********************" />
            <echo message="********** ${output.dir}/${war.name} to ${jboss.home}/standalone/deployments **********" />
            <copy todir="${jboss.home}/standalone/deployments/">
                <fileset dir="${output.dir}/">
                  <include name="${war.name}"/>
                </fileset>
            </copy>
            <echo message="*******************  Deployed Successfully   *********************" />
        </target>
</project>

NOTE: The only change in the above file you need to do is to change the “jboss.home” directory path in the second line of the above script to point to your own JBoss AS7 directory.

Step9). Now before running your ANT script to build and deploy the above webapplication you should have the ANT as well as JAVA set in the $PATH variable of the Shell / command prompt as following:

For Unix Based OS:
export PATH=/home/userone/jdk1.6.0_21/bin:/home/userone/org.apache.ant_1.6.5/bin:$PATH

For Windows Based OS:
set PATH=C:/jdk1.6.0_21/bin;C:/org.apache.ant_1.6.5/bin;%PATH%

Step10). Now once the PATH is set In the command/Shell prompt you can move inside the directory “/home/userone/JPA2_And_Toplink_On_AS7” and then run the ant to build the webservice. by running the command “ant deploy”

Buildfile: build.xml

init:
   [delete] Deleting directory /home/userone/JPA2_And_Toplink_On_AS7/build
    [mkdir] Created dir: /home/userone/JPA2_And_Toplink_On_AS7/build
    [mkdir] Created dir: /home/userone/JPA2_And_Toplink_On_AS7/tmp
    [mkdir] Created dir: /home/userone/JPA2_And_Toplink_On_AS7/tmp/WEB-INF/classes/META-INF

build:
    [javac] Compiling 4 source files to /home/userone/JPA2_And_Toplink_On_AS7/tmp/WEB-INF/classes
     [copy] Copying 4 files to /home/userone/JPA2_And_Toplink_On_AS7/tmp/WEB-INF/classes
     [copy] Copying 1 file to /home/userone/JPA2_And_Toplink_On_AS7/tmp
     [copy] Copying 1 file to /home/userone/JPA2_And_Toplink_On_AS7/tmp/WEB-INF
     [copy] Copying 1 file to /home/userone/JPA2_And_Toplink_On_AS7/tmp/WEB-INF/classes/META-INF
      [jar] Building jar: /home/userone/JPA2_And_Toplink_On_AS7/tmp/JPA_BASIC_Demo.war
     [copy] Copying 1 file to /home/userone/JPA2_And_Toplink_On_AS7/build

deploy:
     [echo] *******************  Deploying the WAR file JPA_BASIC_Demo.war *********************
     [echo] ********** build/JPA_BASIC_Demo.war to /home/userone/jboss-as-7.1.1.Final/standalone/deployments **********
     [copy] Copying 1 file to /home/userone/jboss-as-7.1.1.Final/standalone/deployments
     [echo] *******************  Deployed Successfully   *********************

BUILD SUCCESSFUL
Total time: 2 seconds

Step11). Now you will see the following kind of output on your JBoss AS7.1 console which means the application is deployed successfully:

17:50:06,477 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-5) JBAS015876: Starting deployment of "JPA_BASIC_Demo.war"
17:50:06,513 INFO  [org.jboss.as.jpa] (MSC service thread 1-7) JBAS011401: Read persistence.xml for EmployeeService
17:50:06,548 INFO  [org.jboss.as.ejb3.deployment.processors.EjbJndiBindingsDeploymentUnitProcessor] (MSC service thread 1-7) JNDI bindings for session bean named EmployeeService in deployment unit deployment "JPA_BASIC_Demo.war" are as follows:

	java:global/JPA_BASIC_Demo/EmployeeService!jpa.EmployeeServiceRemote
	java:app/JPA_BASIC_Demo/EmployeeService!jpa.EmployeeServiceRemote
	java:module/EmployeeService!jpa.EmployeeServiceRemote
	java:jboss/exported/JPA_BASIC_Demo/EmployeeService!jpa.EmployeeServiceRemote
	java:global/JPA_BASIC_Demo/EmployeeService
	java:app/JPA_BASIC_Demo/EmployeeService
	java:module/EmployeeService

17:50:06,608 INFO  [org.jboss.as.jpa] (MSC service thread 1-6) JBAS011402: Starting Persistence Unit Service 'JPA_BASIC_Demo.war#EmployeeService'
17:50:06,633 INFO  [org.jboss.web] (MSC service thread 1-2) JBAS018210: Registering web context: /JPA_BASIC_Demo
17:50:06,744 INFO  [org.jboss.as.server] (DeploymentScanner-threads - 1) JBAS018565: Replaced deployment "JPA_BASIC_Demo.war" with deployment "JPA_BASIC_Demo.war"

Step12). Now access the WebApplication like following and then fill the form :
http://localhost:8080/JPA_BASIC_Demo/index.jsp

Once you hit the above URL you will see thew following kind of output in oyur JBossAS7 console:

17:52:52,442 INFO  [stdout] (http--127.0.0.1-8080-1) inside TestServlet service()
17:52:52,443 INFO  [stdout] (http--127.0.0.1-8080-1) GOT the UserTransaction       :  org.jboss.tm.usertx.client.ServerVMClientUserTransaction@566f0962
17:52:52,443 INFO  [stdout] (http--127.0.0.1-8080-1) Got jpa.EmployeeServiceRemote :  Proxy for remote EJB StatelessEJBLocator{appName='', moduleName='JPA_BASIC_Demo', distinctName='', beanName='EmployeeService', view='interface jpa.EmployeeServiceRemote'}
17:52:52,459 INFO  [stdout] (http--127.0.0.1-8080-1) 
17:52:52,459 INFO  [stdout] (http--127.0.0.1-8080-1) 	EmployeeService  Object Created. this: jpa.EmployeeService@498eba23
17:52:52,460 INFO  [stdout] (http--127.0.0.1-8080-1) Employee Object Created. this: jpa.Employee@395e758f
17:52:52,460 INFO  [stdout] (http--127.0.0.1-8080-1) 
17:52:52,461 INFO  [stdout] (http--127.0.0.1-8080-1) 	[EmployeeService] Before em.persist(emp)
17:52:52,481 INFO  [stdout] (http--127.0.0.1-8080-1) [EL Info]: 2012-06-10 17:52:52.481--ServerSession(631563432)--EclipseLink, version: Eclipse Persistence Services - 2.3.2.v20111125-r10461
17:52:52,509 INFO  [stdout] (http--127.0.0.1-8080-1) Employee Object Created. this: jpa.Employee@4a44db2a
17:52:52,510 INFO  [stdout] (http--127.0.0.1-8080-1) [EL Info]: 2012-06-10 17:52:52.51--ServerSession(631563432)--vfs:/content/JPA_BASIC_Demo.war/WEB-INF/classes/_EmployeeService login successful
17:52:52,515 INFO  [stdout] (http--127.0.0.1-8080-1) Employee Object Created. this: jpa.Employee@4542ca0
17:52:52,686 INFO  [stdout] (http--127.0.0.1-8080-1) Employee Object Created. this: jpa.Employee@43458a40
17:52:52,687 INFO  [stdout] (http--127.0.0.1-8080-1) Employee Object Created. this: jpa.Employee@3022eec5
17:52:52,687 INFO  [stdout] (http--127.0.0.1-8080-1) Employee Object Created. this: jpa.Employee@4569e033
17:52:52,687 INFO  [stdout] (http--127.0.0.1-8080-1) 
17:52:52,687 INFO  [stdout] (http--127.0.0.1-8080-1) 	[EmployeeService] Before findEmployee(id)
17:52:52,688 INFO  [stdout] (http--127.0.0.1-8080-1) 
17:52:52,688 INFO  [stdout] (http--127.0.0.1-8080-1) 	 Inside findEmployee(2223)
17:52:52,688 INFO  [stdout] (http--127.0.0.1-8080-1) 
17:52:52,689 INFO  [stdout] (http--127.0.0.1-8080-1) 	[EmployeeService] Inside createEmployee() findEmployee result: jpa.Employee@395e758f
17:52:52,690 INFO  [stdout] (http--127.0.0.1-8080-1) Employee Object Created. this: jpa.Employee@1ee69bc3
17:52:52,691 INFO  [stdout] (http--127.0.0.1-8080-1) 
17:52:52,691 INFO  [stdout] (http--127.0.0.1-8080-1) 	 Inside findAllEmployees()
17:52:52,694 INFO  [stdout] (http--127.0.0.1-8080-1) Employee Object Created. this: jpa.Employee@1b3cbd53
17:52:52,694 INFO  [stdout] (http--127.0.0.1-8080-1) Employee Object Created. this: jpa.Employee@30b1a21d
17:52:52,695 INFO  [stdout] (http--127.0.0.1-8080-1) Employee Object Created. this: jpa.Employee@5e0a36e4
17:52:52,696 INFO  [stdout] (http--127.0.0.1-8080-1) Employee Object Created. this: jpa.Employee@7099e2f7
17:52:52,696 INFO  [stdout] (http--127.0.0.1-8080-1) Employee Object Created. this: jpa.Employee@703ffe2
17:52:52,697 INFO  [stdout] (http--127.0.0.1-8080-1) Employee Object Created. this: jpa.Employee@71f1584a
17:52:52,697 INFO  [stdout] (http--127.0.0.1-8080-1) Employee Object Created. this: jpa.Employee@1bdb9cb7
.

=======================================================================

Some Issues You Might Face

=======================================================================

Issue-1

If you dont declare the property name=”jboss.as.jpa.providerModule” value=”org.eclipse.persistence.jpa” in your “persistence.xml” file then you might see following exception while deploying your Toplink JPA:

17:55:32,081 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-4) JBAS015876: Starting deployment of "JPA_BASIC_Demo.war"
17:55:32,081 INFO  [org.jboss.as.server] (DeploymentScanner-threads - 1) JBAS015863: Replacement of deployment "JPA_BASIC_Demo.war" by deployment "JPA_BASIC_Demo.war" was rolled back with failure message {"JBAS014671: Failed services" => {"jboss.module.service."deployment.JPA_BASIC_Demo.war".main" => "org.jboss.msc.service.StartException in service jboss.module.service."deployment.JPA_BASIC_Demo.war".main: Failed to load module: deployment.JPA_BASIC_Demo.war:main"}}
17:55:32,095 INFO  [org.jboss.as.jpa] (MSC service thread 1-8) JBAS011401: Read persistence.xml for EmployeeService
17:55:32,101 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-8) MSC00001: Failed to start service jboss.module.service."deployment.JPA_BASIC_Demo.war".main: org.jboss.msc.service.StartException in service jboss.module.service."deployment.JPA_BASIC_Demo.war".main: Failed to load module: deployment.JPA_BASIC_Demo.war:main
	at org.jboss.as.server.moduleservice.ModuleLoadService.start(ModuleLoadService.java:91) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
	at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
	at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) [rt.jar:1.6.0_24]
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) [rt.jar:1.6.0_24]
	at java.lang.Thread.run(Thread.java:679) [rt.jar:1.6.0_24]
Caused by: org.jboss.modules.ModuleNotFoundException: Module org.eclipse.persistence:main is not found in local module loader @6da28362 (roots: /NotBackedUp/JBoss_All/jboss-as-7.1.1.Final/modules)
	at org.jboss.modules.LocalModuleLoader.findModule(LocalModuleLoader.java:126) [jboss-modules.jar:1.1.1.GA]
	at org.jboss.modules.ModuleLoader.loadModuleLocal(ModuleLoader.java:275) [jboss-modules.jar:1.1.1.GA]
	at org.jboss.modules.ModuleLoader.preloadModule(ModuleLoader.java:222) [jboss-modules.jar:1.1.1.GA]
	at org.jboss.modules.LocalModuleLoader.preloadModule(LocalModuleLoader.java:94) [jboss-modules.jar:1.1.1.GA]
	at org.jboss.modules.Module.addPaths(Module.java:841) [jboss-modules.jar:1.1.1.GA]
	at org.jboss.modules.Module.link(Module.java:1181) [jboss-modules.jar:1.1.1.GA]
	at org.jboss.modules.Module.relinkIfNecessary(Module.java:1207) [jboss-modules.jar:1.1.1.GA]
	at org.jboss.modules.ModuleLoader.loadModule(ModuleLoader.java:208) [jboss-modules.jar:1.1.1.GA]
	at org.jboss.as.server.moduleservice.ModuleLoadService.start(ModuleLoadService.java:70) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
	... 5 more

Issue-2

If you wont start a transaction like following inside your code before persisting an entity in your Database then you will see the following kind of exception in your logs (EmployeeService.java snippet):

    try{ 
         em.getTransaction().begin();
         em.persist(emp);
         em.flush();
         em.getTransaction().commit();
       } 
    catch(Exception e)
       {
          e.printStackTrace();
          try{   em.getTransaction().rollback();   } catch(Exception ee)  {  ee.printStackTrace();  }
       }

Following exceptions you will encounter …

17:57:56,475 ERROR [stderr] (http--127.0.0.1-8080-1) javax.persistence.TransactionRequiredException: 
17:57:56,476 ERROR [stderr] (http--127.0.0.1-8080-1) Exception Description: No transaction is currently active
17:57:56,476 ERROR [stderr] (http--127.0.0.1-8080-1) 	at  org.eclipse.persistence.internal.jpa.transaction.EntityTransactionWrapper.throwCheckTransactionFailedException(EntityTransactionWrapper.java:113)
17:57:56,476 ERROR [stderr] (http--127.0.0.1-8080-1) 	at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionWrapper.checkForTransaction(EntityTransactionWrapper.java:50)
17:57:56,477 ERROR [stderr] (http--127.0.0.1-8080-1) 	at org.eclipse.persistence.internal.jpa.EntityManagerImpl.checkForTransaction(EntityManagerImpl.java:1776)
17:57:56,477 ERROR [stderr] (http--127.0.0.1-8080-1) 	at org.eclipse.persistence.internal.jpa.EntityManagerImpl.flush(EntityManagerImpl.java:780)
17:57:56,477 ERROR [stderr] (http--127.0.0.1-8080-1) 	at org.jboss.as.jpa.container.AbstractEntityManager.flush(AbstractEntityManager.java:439)
17:57:56,477 ERROR [stderr] (http--127.0.0.1-8080-1) 	at jpa.EmployeeService.createEmployee(Unknown Source)
.
.
17:57:56,493 ERROR [stderr] (http--127.0.0.1-8080-1) java.lang.IllegalStateException: 
17:57:56,494 ERROR [stderr] (http--127.0.0.1-8080-1) Exception Description: No transaction is currently active
17:57:56,494 ERROR [stderr] (http--127.0.0.1-8080-1) 	at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.rollback(EntityTransactionImpl.java:122)

<property name=”eclipselink.ddl-generation” value=”create-tables” />
.
.
Thanks
Middleware Magic Team 🙂

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.