An EJB application that demonstrates persistence (with
appropriate business logic).
Step
1: Creation of Project Application
1. File -> New Project -> Java EE ->
Enterprise Application -> click next -> Give name for project (ex:
employee -> set Java EE version as Java EE 5 -> Finish.
2. At the end of creation you can see three modules
generated.
Step
2: Creation of Entity Bean
1. Right click on projects ejb module -> new ->
Entity class -> Give class name and package -> click next -> Select
data source with your database -> Finish.
2. Change AUTO to IDENTITY and add the following code
String name;
int salary;
3. Select the variables -> right click over the
selection -> insert code -> Getter and Setter… -> select all ->
Generate. You can see getter and setter method generated.
Step
3: Creation of Session bean for Entity Class
1. Right click on projects ejb module -> new ->
Other -> Enterprise Java beans -> Session bean for entity classes ->
click Add all -> click next -> select local.
Step
4: Creating Servlet file
1. Right click on project war module -> new ->
servlet -> Give name for servlet and package -> next -> finish.
2. Inside the class definition -> Right click ->
Insert code -> call enterprise bean -> select your entity class( ex:
EmployeeFacade) -> click ok.
3. Inside processRequest method add the following code,
employee dan=new employee();
dan.setName(request.getParameter("name"));
dan.setSalary(Integer.parseInt(request.getParameter("salary")));
empFacade.create(dan);
4. Left click on the error of first line code -> Add
import (for your entity class).
Step
5: Creating jsp file
1. Change the code in index.jsp with your code.
2. Your code should produce two label and 2 text boxes
and make sure that mapping servlet with jsp file done correctly.
Step
6: Executing the project
1. Right click on Application module -> Clean and
bulid -> Right click on Application module -> Deploy.
2. Under services window -> right click on glassfish
server -> start the server ->
right click on glassfish server ->
view admin console ->
Applications -> click on entity bean class name -> Launch -> click on
first link -> Enter data and submit->
3. You can see the data on database by -> right
click on your database -> refresh -> expand your table -> view data.
//prog13:An EJB application that
demonstrates Entity Bean (persistence).
//employee.java in prog13-ejb
package
eb;
import
java.io.Serializable;
import
javax.persistence.Entity;
import
javax.persistence.GeneratedValue;
import
javax.persistence.GenerationType;
import
javax.persistence.Id;
@Entity
public
class employee implements Serializable {
private
static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy
= GenerationType.IDENTITY)
private
Long id;
String name;
int
salary;
public
String getName() {
return
name;
}
public
void setName(String name) {
this.name = name;
}
public
int getSalary() {
return
salary;
}
public
void setSalary(int salary) {
this.salary = salary;
}
public
Long getId() {
return
id;
}
public
void setId(Long id) {
this.id = id;
}
@Override
public
int hashCode() {
int
hash = 0;
hash
+= (id != null ? id.hashCode() : 0);
return
hash;
}
@Override
public
boolean equals(Object object) {
// TODO: Warning - this method won't
work in the case the id fields are not set
if
(!(object instanceof employee)) {
return
false;
}
employee
other = (employee) object;
if
((this.id == null && other.id != null) || (this.id != null &&
!this.id.equals(other.id))) {
return
false;
}
return
true;
}
@Override
public
String toString() {
return
"eb.employee[ id=" + id + " ]";
}
}
//AbstractFacade.java in prog13-ejb
package
eb;
import
java.util.List;
import
javax.persistence.EntityManager;
public
abstract class AbstractFacade<T> {
private
Class<T> entityClass;
public
AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}
protected
abstract EntityManager getEntityManager();
public
void create(T entity) {
getEntityManager().persist(entity);
}
public
void edit(T entity) {
getEntityManager().merge(entity);
}
public
void remove(T entity) {
getEntityManager().remove(getEntityManager().merge(entity));
}
public
T find(Object id) {
return
getEntityManager().find(entityClass, id);
}
public
List<T> findAll() {
javax.persistence.criteria.CriteriaQuerycq
= getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return
getEntityManager().createQuery(cq).getResultList();
}
public
List<T> findRange(int[] range) {
javax.persistence.criteria.CriteriaQuery
cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
javax.persistence.Query
q = getEntityManager().createQuery(cq);
q.setMaxResults(range[1]
- range[0]);
q.setFirstResult(range[0]);
return
q.getResultList();
}
public
int count() {
javax.persistence.criteria.CriteriaQuery
cq = getEntityManager().getCriteriaBuilder().createQuery();
javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
cq.select(getEntityManager().getCriteriaBuilder().count(rt));
javax.persistence.Query
q = getEntityManager().createQuery(cq);
return
((Long) q.getSingleResult()).intValue();
}
}
//employeeFacade.java in prog13-ejb
package
eb;
import
javax.ejb.Stateless;
import
javax.persistence.EntityManager;
import
javax.persistence.PersistenceContext;
@Stateless
public
class employeeFacade extends AbstractFacade<employee> implements
employeeFacadeLocal {
@PersistenceContext(unitName
= "prog13-ejbPU")
private
EntityManager em;
protected
EntityManager getEntityManager() {
return
em;
}
public
employeeFacade() {
super(employee.class);
}
}
//employeeFacadeLocal.java in
prog13-ejb
package
eb;
import
java.util.List;
import
javax.ejb.Local;
@Local
public
interface employeeFacadeLocal {
void
create(employee employee);
void
edit(employee employee);
void
remove(employee employee);
employee
find(Object id);
List<employee>findAll();
List<employee>findRange(int[] range);
int
count();
}
//index.jsp in prog13-war
<%@page
contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE
html>
<html>
<head>
<meta
http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>Employee
Detail</title>
</head>
<body
bgcolor="orange">
<form
action="emp" method="get">
<h1>
Servlet EJB Session Entity Bean </h1>
Employee
Name: <input type="textbox" size="12"
name="name"/><br/>
Employee
Salary: <input type="textbox" size="5"
name="salary"/><br/>
<input
type="submit" name="submit" value="submit"/>
<input
type="reset" name="clear" value="clear">
</form>
</body>
</html>
//emp.java in prog13-war
package
p13;
import
eb.employee;
import
eb.employeeFacadeLocal;
import
java.io.IOException;
import
java.io.PrintWriter;
import
javax.ejb.EJB;
import
javax.servlet.ServletException;
import
javax.servlet.http.HttpServlet;
import
javax.servlet.http.HttpServletRequest;
import
javax.servlet.http.HttpServletResponse;
public
class emp extends HttpServlet {
@EJB
private
employeeFacadeLocal employeeFacade;
protected
void processRequest(HttpServletRequest request, HttpServletResponse response)
throws
ServletException, IOException {
employee
dan=new employee();
dan.setName(request.getParameter("name"));
dan.setSalary(Integer.parseInt(request.getParameter("salary")));
employeeFacade.create(dan);
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try
{
} finally {
out.close();
}
}
@Override
protected
void doGet(HttpServletRequest request, HttpServletResponse response)
throws
ServletException, IOException {
processRequest(request,
response);
}
@Override
protected
void doPost(HttpServletRequest request, HttpServletResponse response)
throws
ServletException, IOException {
processRequest(request,
response);
}
@Override
public
String getServletInfo() {
return
"Short description";
}
}