Life cycle callback methods of Entities

Below example demostrate how to use lifecycle callback handler methods in EJB 3

Below steps are how to use life cycle callback methods in Entities :

  • Create Database JNDI on Oracle WebLogic Server
  • Create table in MySQL database
  • Create Enterprise Application Project EJB3EntitiesLifecycle.ear
  • Create listener class
  • Create POJO (Entity ) class
  • Create Stateless Session Bean with Local interface
  • Create META-INF\persistence.xml
  • Create index.jsp in Web project
  • Create Servlet in Web project
  • Verify the project directory structure
  • Run the Application

Step 1: Create Database JNDI on Oracle WebLogic Server 10.3.2
Click here to how to create Database JNDI on Oracle WebLogic Server 10.3.2

Step 2: Create table in MySQL database
Create table a below specifications :
Database name : test
Table Name : Employee
Schema :
Create table Employee
(
EId varchar(20) primary key,
Name varchar(40),
City varchar(20),
Salary double
);

Step 3: Create Enterprise Application Project EJB3EntitiesLifecycle.ear with EJB (EJB3EntitiesLifecycleEJB) and Web (EJB3EntitiesLifecycleWeb) Module
Click here - How to create Enterprise Application Project

picture
Specify the Enterprise Application Project name EJB3EntitiesLifecycle and click Next.

Below screen is used to create EJB and Web module in Enterprise Application Project. Click New Module


Step 4: Create Listener class EntityListener.java
package techmyguru.entities;
// all imports
public class EntityListener 
{
@PrePersist
public void beforePersist() {
System.out.println("Before Persist");
}
@PostPersist
public void afterPersist() {
System.out.println("After Persist");
}
@PreUpdate
public void beforeUpdate() {
System.out.println("Before Update");
}
@PostUpdate
public void afterUpdate() {
System.out.println("After Update");
}
@PreRemove
public void beforeRemove() {
System.out.println("Before Remove");
}

@PostRemove
public void afterRemove() {
System.out.println("After Remove");
}

@PostLoad
public void afterLoad() {
System.out.println("After Load");
}
}

Step 5: Create POJO (Entity ) class Employee.java
package techmyguru.entities;
// all imports
@Entity
<b>@EntityListeners({EntityListener.class})</b>
@Table(name="employee")
public class Employee {
@Id
private String eid;
private String name;
private String city;
private double salary;
public Employee() {  }
public Employee(String eid, String name, String city, double salary)
{
  this.eid = eid;
  this.name = name;
  this.city = city;
  this.salary = salary;
}
// all getter and setter methods
@Override
public String toString()
{
    return eid+"  "+name+" "+city+" "+salary;
}
}

Step 6: Create Stateless Session Bean class EmployeeEntities and local interface EmployeeEntitiesLocal -
This step will create two java file. One will be local interface EmployeeEntitiesLocal.java and other will be bean class EmployeeEntities.java.

EmployeeEntitiesLocal.java
package techmyguru.entities;
import java.util.List;
import javax.ejb.Local;
@Local
public interface EmployeeEntitiesLocal 
{
public String addEmp(Employee emp);
public Employee queryEmp(String id);
public String updateEmp(Employee emp);
public String deleteEmp(String id);
public List<Employee> getAllEmp();
}

EmployeeEntities.java
package techmyguru.entities;
// all import statements
@Stateless
public class EmployeeEntities implements EmployeeEntitiesLocal 
{
@PersistenceContext(unitName = "EntityDemo")
private EntityManager em;

@Override
public String addEmp(Employee emp
{
  em.persist(emp);
  System.out.println("Insert "+emp);
  return "Inserted";
}

@Override
public Employee queryEmp(String id
{
  Employee emp = (Employeeem.find(Employee.class, id);
  return emp;
}

@Override
public String updateEmp(Employee emp
{
  Employee emp1=(Employee)em.find(Employee.class,emp.getEid());
  System.out.println("Update Old ="+emp1);
  emp1.setCity(emp.getCity());
  emp1.setSalary(emp1.getSalary() + emp.getSalary());
  em.merge(emp1);
  System.out.println("Update New ="+emp1);
  return "updated";
}

@Override
public String deleteEmp(String id
{
  Employee emp = (Employeeem.find(Employee.class, id);
  em.remove(emp);
  System.out.println("Delete "+emp);
  return "Deleted";
}

@Override
public List<Employee> getAllEmp() 
{
  List<Employee> emps =em.createQuery("select e from Employee as e")
           .getResultList();
  return emps;
}
}

Step 7: Create META-INF\persistence.xml
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.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_1_0.xsd">
<persistence-unit name="EntityDemo" transaction-type="JTA">
  <jta-data-source>jndi1</jta-data-source>
  <class>techmyguru.entities.Employee</class>
  <exclude-unlisted-classes>false</exclude-unlisted-classes>
  <properties />
</persistence-unit>
</persistence>

Step 8: Create index.jsp in Web project
<%@page import="techmyguru.entities.Employee"%>
<%@page import="java.util.Iterator"%>
<%@page import="java.util.List"%>
<html>
<head>
<title>Insert title here</title>
<style type="text/css">
table, td,th
{
border-collapse: collapse;
border: 1px solid blue;
}
</style>
</head>
<body>
<h3>
<form action="EntitiesServlet" method="POST">

<table border="0" align="left" width="60%">
<tbody>
<tr>
  <td colspan="2" align="left">Entities (ORMCRUD</td>
</tr>
<tr>
  <td>Enter Employee Id</td>
  <td><input type="text" name="id" value="" /></td>
</tr>
<tr>
  <td>Name</td>
  <td><input type="text" name="name" value="" /></td>
</tr>
<tr>
  <td>City</td>
  <td><input type="text" name="city" value="" /></td>
</tr>
<tr>
  <td>Salary</td>
  <td><input type="text" name="salary" value="0" /></td>
</tr>
<tr>
  <td align="left"><input type="submit" name="submit" value="Add Emp" />
  </td>
  <td align="left"><input type="submit" name="submit" value="Modify Emp" />
  </td>
</tr>
<tr>
  <td align="left"><input type="submit" name="submit" value="Delete Emp" />
  </td>
  <td align="left"><input type="submit" name="submit" value="Find All" />
  </td>
</tr>
</tbody>
</table>
</form>
<hr>
<%
Object msg=request.getAttribute("msg");
if(msg!=null)
out.println(msg.toString());  
Object emp=request.getAttribute("emplist");
if(emp!=null)
{
List<Employee> emplist=(List)emp;
Iterator<Employee> empitr=emplist.iterator();
out.println("<table align='left' width='80%'>");
out.println("<tr><th>Emp Id</th><th>Name</th><th>City</th>"+
      "<th>Salary</th></tr>");
while(empitr.hasNext())
{
Employee emp1=empitr.next();
%>
<tr>
<td><%= emp1.getEid() %></td>
<td><%= emp1.getName() %></td>
<td><%= emp1.getCity() %></td>
<td><%= emp1.getSalary() %></td>
</tr>
<%
}
out.println("</table>");
}
%>
</h3>
</body>
</html>

Step 9: Create Servlet in Web project
EntitiesServlet.java
package techmyguru.web;
// all import statements
public class EntitiesServlet extends HttpServlet 
{
private static final long serialVersionUID = 1L;
@EJB
EmployeeEntitiesLocal local;

protected void doPost(HttpServletRequest request,
HttpServletResponse responsethrows ServletException, IOException 
  {
  try {
  String action = request.getParameter("submit");
  if (action.trim().equals("Add Emp")) 
  {
  Employee emp = new Employee(request.getParameter("id").trim()
  request.getParameter("name").trim()
  request.getParameter("city").trim(),
  Double.parseDouble(request.getParameter("salary").trim()));
  request.setAttribute("msg",local.addEmp(emp));
  forwardPage(request, response);
  else if (action.trim().equals("Query Emp")) 
  {
  String id = request.getParameter("id").trim();
  Employee empvo = local.queryEmp(id);
  else if (action.trim().equals("Modify Emp")) 
  {
  Employee empvo = new Employee(request.getParameter("id").trim()
  request.getParameter("name").trim()
  request.getParameter("city").trim(),
  Double.parseDouble(request.getParameter("salary").trim()));
  request.setAttribute("msg",local.updateEmp(empvo));
  forwardPage(request, response);
  else if (action.trim().equals("Delete Emp")) 
  {
  String id = request.getParameter("id").trim();
  request.setAttribute("msg",local.deleteEmp(id));
  forwardPage(request, response);
  
  else
  {
  request.setAttribute("msg","");
  forwardPage(request, response);
  }
  catch (Exception e) {
  }
  }
  @Override
  protected void doGet(HttpServletRequest request, 
       HttpServletResponse response)
  throws ServletException, IOException {
  request.setAttribute("msg","");
  try {
  forwardPage(request, response);
  catch (Exception e) {
  e.printStackTrace();
  }
  }
  public void forwardPage(HttpServletRequest request,
  HttpServletResponse responsethrows Exception
  {
  List<Employee> list1 = local.getAllEmp();
  request.setAttribute("emplist",list1);
  RequestDispatcher rd=request.getRequestDispatcher("index.jsp");
  rd.forward(request, response);
  }
}

Step 10: Verify the project directory structure


Step 11: Run the Application
Right click on Web Project -> Run As -> Run on Server
and Enter the values and click respective button to perform taks.
You will get below output on server console-




Previous Download Source Code Next

Comment by : Mei October 3rd, 2015
Comment : There is an error in the code...You cannot call non staitc method from within staitc method..()To make the code work you must change "int fun()" to "staitc int fun()"


Write your Comment

Name :
Email Id : [ We will not publish your email id ]
Your Comment : [ Maximum 200 chars ]
Enter Security code