EJB3 and JPA step by step tutorial using Eclipse

In this tutorial I am going to explain step by step tutorial to create an EJB 3 Project with JPA in Eclipse IDE.

This tutorial will explain how to create a simple EJB 3 JPA project and a remote Java application client which calls the bean method.

We will create a JPA entity and a stateless session bean to perform operations on the entity.For testing this JPA example we have written a remote Java Application Client.


Tools Used to develop this Application :

  1. JDK 6 (Java SE 6)
  2. EJB 3.0 (stateless session bean)
  3. Eclipse Indigo
  4. JBoss Application Server (AS) 5.1.0
  5. EJB 3.0 Java Persistence API (JPA)

Here I am going to explain step by step tutorial to create an EJB 3 Project with JPA application in Eclipse IDE.

This tutorial will explain how to create a simple EJB 3 JPA project and a remote Java application client which calls the bean method.

We will create a JPA entity and a stateless session bean to perform operations on the entity.For testing this JPA example we have written a remote Java Application Client.


Tools Used to develop this Application :

  1. JDK 6 (Java SE 6)
  2. EJB 3.0 (stateless session bean)
  3. Eclipse Indigo
  4. JBoss Application Server (AS) 5.1.0
  5. EJB 3.0 Java Persistence API (JPA)





Creating Database and data-source :

First of all create a database called ems. You can use MySQL GUI tool like MySQL Query Browser or MySQL Work Bench to create a database.

Configuring datasource in JBoss :

The data source configuration should be defined in a file with a suffix of *-ds.xml.We can deploy this file either in JBossAS_HOME/server/default/deploy directory or Your EJB project's META-INFdirectory.

If you are using jboss deploy(JBossAS_HOME/server/default/deploy) directory for the deployment of *-ds.xml file, then any application deployed in this application server can use this configuration file, i.e one time deployment.

If you are using your EJB project's META-INF directory for the deployment of ds file, then you have to do this in every project which uses MySQL datasource.

Go to your jboss-home\docs\examples\jca inside that folder there is file called mysql-ds.xml.Copy this file to JBossAS_HOME/server/default/deploy directory of your jboss server.Then we need to add database details to that file.

<?xml version="1.0" encoding="UTF-8"?>

<!-- $Id: mysql-ds.xml 41017 2006-02-07 14:26:14Z acoliver $ -->
<!--  Datasource config for MySQL using 3.0.9 available from:
http://www.mysql.com/downloads/api-jdbc-stable.html
-->

<datasources>
  <local-tx-datasource>
    <jndi-name>EmpMgtDS</jndi-name>
    <connection-url>jdbc:mysql://localhost:3306/studentmgt_db</connection-url>
    <driver-class>com.mysql.jdbc.Driver</driver-class>
    <user-name>root</user-name>
    <password>mukesh</password>
    <exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter</exception-sorter-class-name>
    <!-- should only be used on drivers after 3.22.1 with "ping" support
    <valid-connection-checker-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLValidConnectionChecker</valid-connection-checker-class-name>
    -->
    <!-- sql to call when connection is created
    <new-connection-sql>some arbitrary sql</new-connection-sql>
      -->
    <!-- sql to call on an existing pooled connection when it is obtained from pool - MySQLValidConnectionChecker is preferred for newer drivers
    <check-valid-connection-sql>some arbitrary sql</check-valid-connection-sql>
      -->

    <!-- corresponding type-mapping in the standardjbosscmp-jdbc.xml (optional) -->
    <metadata>
       <type-mapping>mySQL</type-mapping>
    </metadata>
  </local-tx-datasource>
</datasources>


Creating New EJB Project :

Open Eclipse IDE and create a new EJB project by selecting File -> New -> EJB Project

EJB3 and JPA Application

Name the Project as EmployeeManagementEJB.Make sure that Target Runtime as JBoss 5.1 Runtime EJB Module version as 3.0.

EJB3 and JPA Application

Click Next -> Next -> and Finish.You will see an EJB project in the Project Explorer view as shown below.

EJB3 and JPA Application


Creting persistence.xml in META-INF directory :

Persistence units are defined in persistence.xml file, which has to be located in the META-INF directory in the classpath.The EntityManager is created by the EntitiyManagerFactory which is configured by the persistence unit.

The persistence unit is described via the file "persistence.xml .This file defines the connection data to the database, e.g. the driver, the user and the password details.

Right click on META-INF folder -> New -> Other -> XML -> XML file. Enter the file name as persistence.xml and finish.

EJB3 and JPA Application

Add following code in your persistence.xml file.

<?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="EmpMgmtPU" transaction-type="JTA">
		<jta-data-source>java:/EmpMgtDS</jta-data-source>
		<properties>
			<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
			<property name="hibernate.hbm2ddl.auto" value="create" />
		</properties>
	</persistence-unit>
</persistence>

Note:- In our data-source file JNDI name is EmpMgtDS as <jndi-name>EmpMgtDS</jndi-name> so in persistence.xml file we need to add java:/jndi-name under <jta-data-source> name. In our case <jta-data-source> name is java:/EmpMgtDS, so in xml file <jta-data-source>java:/EmpMgtDS</jta-data-source> should be added.



Creating JPA Entity Class :

In this Example we are going to persist "Employee Entity class which is a Plain Old Java Object class (POJO). These persistence operation will be performed using Java Persistence API and require minimum JDK 5.0.

Entity Class Rules

  • Entity Class must have @Entity annotaion
  • Must have a public or protected no-arg constructor
  • If it passed as a detached object through a remote interface,then it Must implement Serializable interface.
  • It must contain an id annotated with @Id

Create Entity Class Employee.java in com.jwt.ejb.entity package.Add following code into this class.

Employee.java

package com.jwt.ejb.entity;

import java.io.Serializable;
import javax.persistence.*;

@Entity
@Table(name = "EMPLOYEE")
public class Employee implements Serializable {

	private static final long serialVersionUID = 1L;
	@Id
	@GeneratedValue
	@Column(name = "id")
	private Integer id;

	@Column(name = "first_name", length = 50)
	private String firstName;

	@Column(name = "last_name", length = 50)
	private String lastName;

	@Column(name = "email", length = 50)
	private String email;

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
}

Creating Session Bean and Bean Interface :

Right click on ejbModule -> New -> Session Bean (EJB 3.x).

EJB3 and JPA Application

  • Enter the Java package name as com.jwt.ejb.business.impl
  • Enter the Class name as ManageEmployeeBean
  • Select the State type as Stateless
  • Check the Remote Business Interface and enter the name as com.jwt.ejb.business.EmployeeRemote.
  • Click Finish

EJB3 and JPA Application


Implementing Bean and Bean Interface :

Open Bean Interface EmployeeRemote.java and declare the business method addEmployee() in that interface. Copy following code in that interface.

EmployeeRemote.java
package com.jwt.ejb.business;

import javax.ejb.Remote;

import com.jwt.ejb.entity.Employee;

@Remote
public interface EmployeeRemote {
	public boolean addEmployee(Employee employee);

}

Open ManageEmployeeBean and type the following code in this.

ManageEmployeeBean.java
package com.jwt.ejb.business.impl;

import com.jwt.ejb.business.EmployeeRemote;
import com.jwt.ejb.entity.Employee;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 * Session Bean implementation class ManageEmployeeBean
 */
@Stateless
public class ManageEmployeeBean implements EmployeeRemote {

	@PersistenceContext(unitName = "EmpMgmtPU")
	private EntityManager entityManager;

	public ManageEmployeeBean() {

	}

	public boolean addEmployee(Employee employee) {
		entityManager.persist(employee);
		return true;
	}

}

Adding MySQL Connector JAR file :

The connector can be downloaded from:Here

JAR file can be deployed either in,

  • JBossAS_HOME/server/default/lib or JBossAS_HOME/server/default/deploy folder so that any application deployed on this server can use this JAR file.

  • Project's build path. Right click on your EJB Project->Properties, select Java Build Path from left side pane and select Libraries from right side and click on 'Add External JARs' and select the mysql-connector-java-5.1.18-bin.jar from your system.

We have created mysql-ds.xml in project's META-INF folder and placed mysql-connector-java-5.1.18-bin.jar in JBossAS_HOME/server/default/lib folder.


Deploying the project :

Now we need to deploy the our EJB Project on server.Follow the steps mentioned below to deploy this project on server.

Start the server

Right click on "JBoss 5.1 Runtime Server" from Servers view and click on Start.

EJB3 and JPA Application


Deploy the Application :

Right click on "JBoss 5.1 Runtime Server" available in Servers view -> Add and Remove. -> Select the EmployeeManagementEJB JAR file from the left pane and click Add and then Finish.

EJB3 and JPA Application

EJB3 and JPA Application

If the project is deployed properly with global JNDI mapping then you will see the following message in the console.

EJB3 and JPA Application

Now check the database, employee table is created there.

EJB3 and JPA Application


Creating Client :

The next step is to write a remote Java client application (with main()) for accessing and invoking the EJBs deployed on the server.

Client uses JNDI to lookup for a proxy of your bean and invokes method on that proxy.

Create a package com.jwt.ejb.client and create a class Client in this package. After creation of the class add following code into this class.

Client.java
package com.jwt.ejb.client;

import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import com.jwt.ejb.business.EmployeeRemote;
import com.jwt.ejb.entity.Employee;

public class Client {
	public static void main(String[] args) {
		EmployeeRemote remote = doLookup();
		Employee employee = new Employee();
		employee.setFirstName("Mukesh");
		employee.setLastName("Kumar");
		employee.setEmail("mrajnitro@gmail.com");

		Employee employee1 = new Employee();
		employee1.setFirstName("Ravi");
		employee1.setLastName("Raj");
		employee1.setEmail("ravi@gmail.com");
		remote.addEmployee(employee);
		remote.addEmployee(employee1);
	}

	private static EmployeeRemote doLookup() {
		Context context = null;
		EmployeeRemote bean = null;
		try {
			// 1. Obtaining Context
			context = getInitialContext();
			// 2. Lookup and cast
			bean = (EmployeeRemote) context.lookup(LOOKUP_STRING);
		} catch (NamingException e) {
			e.printStackTrace();
		}
		return bean;
	}

	private static final String LOOKUP_STRING = "ManageEmployeeBean/remote";
	/*
	 *  * location of JBoss JNDI Service provider the client will use. It should
	 * be * URL string.
	 */
	private static final String PROVIDER_URL = "jnp://localhost:1099";
	/*
	 *  * specifying the list of package prefixes to use when loading in URL *
	 * context factories. colon separated
	 */
	private static final String JNP_INTERFACES = "org.jboss.naming:org.jnp.interfaces";
	/*
	 *  * Factory that creates initial context objects. fully qualified class
	 * name.
	 */
	private static final String INITIAL_CONTEXT_FACTORY = "org.jnp.interfaces.NamingContextFactory";
	private static Context initialContext;

	public static Context getInitialContext() throws NamingException {
		if (initialContext == null) {
			// Properties extends HashTable
			Properties prop = new Properties();
			prop.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
			prop.put(Context.URL_PKG_PREFIXES, JNP_INTERFACES);
			prop.put(Context.PROVIDER_URL, PROVIDER_URL);
			initialContext = new InitialContext(prop);
		}
		return initialContext;
	}
}

Run the Client :

Press Ctrl + F11 to run the client.

Now test the database data is inserted or not? If everything is fine you will see the data is inserted successfully as shown below.

EJB3 and JPA Application




comments powered by Disqus