CRUD in Stateless Session Bean

Below example demostractes how to perform database tasks in Stateless Session Bean

Below steps are to create Stateless session bean :

  • Create database JNDI on Oracle WebLogic Server
  • Create Enterprise Application Project StatelessCRUD.ear.
  • Create table in MySQL database
  • Create Stateless Session Bean with Local interface in EJB project.
  • Create index.jsp in Web project.
  • Create Servlet in Web project.
  • 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 Enterprise Application Project StatelessCRUD.ear with EJB (StatelessCRUDEJB) and Web (StatelessCRUDWeb) Module
Click here if you are not familiear how to create Enterprise Application Project


Specify the Enterprise Application Project name StatelessCRUD and click Next.

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


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

Step 4: Create Stateless Session Bean class EmployeeCRUDSession and local interface EmployeeCRUDSessionLocal :

This step will create two java file. One will be local interface EmployeeCRUDSessionLocal.java and other will be bean class EmployeeCRUDSession.java.

Create POJO class Employee.java
package techmyguru.stateless.crud;
public class Employee {
  private String id, name, city;
  private double salary;

  // constructor is not allowed in production version in POJO
  public Employee() {  }

  public Employee(String id, String name, String city, double salary) {
    this.id = id;
    this.name = name;
    this.city = city;
    this.salary = salary;
  }
// all getter and setter methods

  @Override
  public String toString() {
    return id + "\t" + name + "\t" + city + "\t" + salary;
  }

}

EmployeeCRUDSessionLocal.java
package techmyguru.stateless.crud;
import java.util.ArrayList;
import javax.ejb.Local;
@Local
public interface EmployeeCRUDSessionLocal 
{
public String addEmp(Employee empthrows Exception;
public Employee queryEmp(String idthrows Exception;
public String updateEmp(Employee empthrows Exception;
public String deleteEmp(String idthrows Exception;
public ArrayList<Employee> getAllEmp() throws Exception;
}

EmployeeCRUDSession.java
package techmyguru.stateless.crud;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.ArrayList;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.sql.DataSource;

@Stateless
public class EmployeeCRUDSession implements EmployeeCRUDSessionLocal 
{
@Resource(name = "jndi1")
DataSource datasource;

Connection con;

@Override
public String addEmp(Employee empthrows Exception {
  con = datasource.getConnection();
  String sql = "insert into emp values('" + emp.getId() "','"
      + emp.getName() "','" + emp.getCity() "',"
      + emp.getSalary() ")";
  System.out.println("insert statement \t" + sql);
  con.createStatement().executeUpdate(sql);
  con.close();
  return "Inserted";
}

@Override
public Employee queryEmp(String idthrows Exception {
  Employee emp = new Employee();
  con = datasource.getConnection();
  String sql = "select * from emp where id='" + id + "'";
  System.out.println("query statement is \t" + sql);
  ResultSet res = con.createStatement().executeQuery(sql);
  if (res.next()) {
    emp.setId(res.getString("id"));
    emp.setName(res.getString("name"));
    emp.setCity(res.getString("city"));
    emp.setSalary(res.getDouble("salary"));
  }
  con.close();
  return emp;
}

@Override
public String updateEmp(Employee empthrows Exception {
  con = datasource.getConnection();
  String sql = "update emp set city='" + emp.getCity()
    "',salary=salary+" + emp.getSalary() " where id='"
    + emp.getId() "'";
  System.out.println("update statement \t" + sql);
  con.createStatement().executeUpdate(sql);
  con.close();
  return "updated";
}

@Override
public String deleteEmp(String idthrows Exception {
  con = datasource.getConnection();
  String sql = "delete from emp where id='" + id + "'";
  System.out.println("delete statement is \t" + sql);
  con.createStatement().executeUpdate(sql);
  con.close();
  return "deleted";
}

@Override
public ArrayList<Employee> getAllEmp() throws Exception {
  ArrayList<Employee> list = new ArrayList<Employee>();
  con = datasource.getConnection();
  String sql = "select * from emp";
  System.out.println("get all Employees statement is \t" + sql);
  ResultSet res = con.createStatement().executeQuery(sql);
  while (res.next()) {
  list.add(new Employee(res.getString("id"), res.getString("name"),
  res.getString("city"), res.getDouble("salary")));
  }
  con.close();
  return list;
}
}

Step 5: Add EJB Project to Web project
Right Click on Web Project - > Properties - > Java Build Path -> Click Projects -> Add -> Select StatelessCRUDEJB.

Step 6: Create index.jsp in Web project
<%@page import="techmyguru.stateless.crud.Employee"%>
<%@page import="java.util.Iterator"%>
<%@page import="java.util.ArrayList"%>
<html>
<head>
<title>Stateless CRUD</title>
<style type="text/css">
table, td,th
{
border-collapse: collapse;
border: 1px solid blue;
}
</style>
</head>
<body>
<h3>
<form action="EmpServlet1" method="POST">

<table border="0" align="center" width="60%">
<tbody>
<tr>
  <td colspan="2" align="center">Stateless CRUD</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="right"><input type="submit" name="submit" value="Add Emp" />
  </td>
  <td align="right"><input type="submit" name="submit" value="Modify Emp" />
  </td>
</tr>
<tr>
  <td align="right"><input type="submit" name="submit" value="Delete Emp" />
  </td>
  <td align="right"><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)
{

ArrayList<Employee> emplist=(ArrayList)emp;
Iterator<Employee> empitr=emplist.iterator();
out.println("<table align='center' 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.getId() %></td>
<td><%= emp1.getName() %></td>
<td><%= emp1.getCity() %></td>
<td><%= emp1.getSalary() %></td>
</tr>
<%
}
out.println("</table>");
}
%>
</h3>
</body>
</html>

Step 7: Create Servlet EmpServlet1.java in Web project
package techmyguru.web;
import java.io.IOException;
import java.util.ArrayList;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import techmyguru.stateless.crud.Employee;
import techmyguru.stateless.crud.EmployeeCRUDSessionLocal;

public class EmpServlet1 extends HttpServlet 
{
  private static final long serialVersionUID = 1L;
       
  @EJB
  EmployeeCRUDSessionLocal emplocal;

  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",emplocal.addEmp(emp));
  forwardPage(request, response);

  else if (action.trim().equals("Query Emp")) {
  String id = request.getParameter("id").trim();
  Employee empvo = emplocal.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",emplocal.updateEmp(empvo));
  forwardPage(request, response);
  else if (action.trim().equals("Delete Emp")) {
  String id = request.getParameter("id").trim();
  request.setAttribute("msg",emplocal.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
  {
  ArrayList<Employee> list1 = emplocal.getAllEmp();
  request.setAttribute("emplist",list1);
  RequestDispatcher rd=request.getRequestDispatcher("index.jsp");
  rd.forward(request, response);
  }
}

Step 8: Verify the directory structure as below -


Step 9: Run the Application
Right click on Web Project -> Run As -> Run on Server

Enter the values and click respective button to perform taks.

You will get below output -

Previous Download Source Code Next

Comment by : mmoohh November 23rd, 2012
Comment : this blog is very important for me


Write your Comment

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