EJB3 and JPA step by step tutorial using Eclipse

Here I explain step by step how to create an EJB 3 with JPA application in Eclipse IDE.
This tutorial is for beginners who want to learn steps to create EJB persistence application with Eclipse and Jboss.

Tools used

Eclipse (Galileo)
MySQL database

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

Then I'm going to create a datasource. Go to your jboss directory  ..jboss-5.1.0.GA\docs\examples\jca inside that folder there is file called mysql-ds.xml. I copied that file to  ...jboss-5.1.0.GA\server\default\deploy. Then you can add your 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:

    <!-- should only be used on drivers after 3.22.1 with "ping" support
    <!-- 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) -->
 Now create EJB project.

Create EJB project in Eclipse

Create a new EJB project called StudentManagementEJB. I use JBoss server as application server.

Create EJB project in Eclipse

Create a xml file called persistence.xml in META-INF directory.

Create persistence.xml in Eclipse


<?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="StudentMgtPU"
   <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
   <property name="hibernate.hbm2ddl.auto" value="create" />

Then we have to create an Entity class. Right click on the project -> New -> Class

  •  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, Must implement Serializable
  •  Must have an id annotated with @Id
I created a entity class called Student.java


package com.sameera.domain;

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

@Table(name = "student")
public class Student implements Serializable {

    private static final long serialVersionUID = 1L;

    @Column(name = "id")
    private Integer id;
    @Column(name = "first_name", length = 100)
    private String firstName;
    @Column(name = "last_name", length = 100)
    private String lastName;
    @Column(name = "email", length = 100)
    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;
Create session beans.

Create a Session Bean in Eclipse

I create a Stateless session bean with Local interface.

Create a Session Bean in Eclipse

I added business methods and added add student code.


package com.sameera.session;

import javax.ejb.Local;

import com.sameera.domain.Student;

 * @author Sameera Jayasekara
public interface ManageStudentSessionBeanLocal {
 public boolean addStudent(Student Student);


package com.sameera.session;

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

import com.sameera.domain.Student;

 * Session Bean implementation class ManageStudentSessionBean
 * @author Sameera Jayasekara
public class ManageStudentSessionBean implements ManageStudentSessionBeanLocal {

 private EntityManager entityManager;

 public boolean addStudent(Student student) {
  return true;


Run EJB application on Jboss server.

Run EJB project in Eclipse

See the server console JNDI bindings.

JNDI bindings in JBoss console

 Now see the database. Student table is created.

Created tables in MySQL Workbench

Now start working on web application.
File -> New -> Dynamic Web Project

Create a Dynamic web project in Eclipse

Go next Select 'Generate web.xml deployment descriptor' and finish.

Right click on web content and create a new jsp called index.jsp.


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>EJB3 JPA Jboss - codesstore.blogspot.com</title>

        <form action="ManageStudentServlet" method="POST">

            <table border="0" width="100%">
                    <td colspan="3">  ${message}</td>
                    <td>First Name</td>
                    <td><input type="text" name="fname" value="" /></td>
                    <td>Last Name</td>
                    <td><input type="text" name="lname" value="" /></td>
                    <td><input type="text" name="email" value="" /></td>
                    <td><input type="submit" value="Add" name="Add" /></td>



Create  a servlet to handle the request.
File -> New -> Servlet

Create a Servlet in Eclipse

Before calling Enterprise beans we have to add the ejb project to build path.

Configure build path in Eclipse

 Go to projects tab and add StudentManagementEJB project.

Configure build path in Eclipse


package com.sameera.controller;

import java.io.IOException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sameera.domain.Student;
import com.sameera.session.ManageStudentSessionBeanLocal;

 * @author Sameera Jayasekara
public class ManageStudentServlet extends HttpServlet {

 private static final long serialVersionUID = 1L;
 private ManageStudentSessionBeanLocal manageStudentSessionBeanLocal;

 public void init(ServletConfig config) throws ServletException {

  try {

   Context context = new InitialContext();
   manageStudentSessionBeanLocal = (ManageStudentSessionBeanLocal) context

  } catch (NamingException e) {


 protected void doGet(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {


 protected void doPost(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {

  String message = "";

  String firstName = request.getParameter("fname");
  String lastName = request.getParameter("lname");
  String email = request.getParameter("email");

  Student student = new Student();

  if (manageStudentSessionBeanLocal.addStudent(student)) {
   message = "Student Successfuly Added";
  } else {
   message = "Student Adding Failed";

  request.setAttribute("message", message);
  RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
  rd.forward(request, response);


I looked up ManageStudentSessionBean/local. You can see server console to find JNDI bindings(see image given above)

You can use @EJB annotaions to dependancy injection in a servlet but I tried it with JBoss that didn't work.Then I used @EJB(mappedName="Test"), @EJB with mappedName attribute( @Stateless(mappedName="Test") also used).Then it worked with remote interface. But I prefer JNDI lookup.

web.xml configuration file looks like this.


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
Now You can run the web application.

Run a web project in Eclipse
 Check the database data will be added.

Project structure in Eclipse

EJB application project structure in Eclipse

Note : I put mysql-connector-java-5.1.5-bin.jar to ...jboss-5.1.0.GA\server\default\lib


  1. Hi Sameera,

    Thanks for the post . I am using GlassFish with JPA + Eclipse. Would you please make a tutorial on this.


    PS: are you available on Skype?

  2. All are superb articles... Thanks a lot

  3. Hi Sameera, good example, now we can use netbeans and generate all these codings.....

    1. Yea. See My EJB JPA Netbeans tutorial http://codesstore.blogspot.com/2012/07/ejb3-and-jpa-step-by-step-tutorial_05.html

  4. Hi Sameera,
    Im a new comer to the JavaBeans.
    I got the following error when starting the JBoss server. What should I do?

    12:12:13,843 ERROR [SchemaExport] schema export unsuccessful

  5. This comment has been removed by the author.

  6. Thanks Sameera...it helped me alot...while learning JPA...

  7. machan sammeera i tried it form Postgres Sql , but not creating tables ,what is the jdbc connector for Postgres

    thanks ,im also from UCSC. Good luck

    1. I haven't tried with Postgres,
      Check this value is 'create'
      property name="hibernate.hbm2ddl.auto" value="create"

      Driver may be

      Driver class: org.postgresql.Driver

      Connection URL:
      jdbc:postgresql://[servername]:[port]/[database name]

  8. Great work, I have a problem with the steps, I'm using Jboss as 7.1, and the directorys jboss-as-7.1/docs/examples/jca and jboss-7.1server/default/deploy don't exist in this version, the file mysql-ds.xml is standalone.xml in this version; how can I do the step of the jboss when you copy the file, where should I copy it?

    Thanks for the tutorial, it's excellent

  9. Great work! Simple and Nice Article.

  10. This is good stuff Sameera. well presented and easy to understand !

  11. HTTP method POST is not supported by this URL