Lara

Hibernate

Sunday(5-2-2017) CRUD Dev in Servlets and JSP by using Hibernate

Index.jsp

<a href="SaveEmployeeServlet">add new employee</a>

newEmp.jsp

<%@page import="com.lara.entity.Education"%>

<%@page import="com.lara.entity.Skill"%>

<%@page import="com.lara.entity.Gender"%>

<%@page import="java.util.List"%>

<%

List<Gender> genders = (List<Gender>) request.getAttribute("genders");

List<Education> educations = (List<Education>) request.getAttribute("educations");

List<Skill> skills = (List<Skill>) request.getAttribute("skills");

%>

 

<form action="SaveEmployeeServlet" method="post">

ID : <input type='text' name='id'/> </br>

First Name : <input type='text' name='firstName'/> </br>

Last Name : <input type='text' name='lastName'/> </br>

House No : <input type='text' name='houseNo'/> </br>

Street Name : <input type='text' name='streetName'/> </br>

Gender : <%

for(Gender gender : genders)

{

%>

<input type='radio' name='gender' value='<%= gender.getId() %>'/> <%= gender.getName() %>

<%} %>

</br>

Skill : <%

for(Skill skill : skills)

{

%>

<input type='checkbox' name='skills' value='<%= skill.getId() %>'/> <%= skill.getName() %>

<%} %>

</br>

Education : <select name='education'>

<option value="0">Select</option>

<%

for(Education education : educations)

{

%>

<option value='<%= education.getId() %>'>

<%= education.getName() %>

</option>

<%} %>

</select>

</br>

<input type='submit' value='submit'/>

</form>

Util HibernateUtil.java

package com.lara.util;

 

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

 

public class HibernateUtil

{

private static SessionFactory sssionFactory;

static

{

Configuration c1 = new Configuration();

c1.configure();

sssionFactory = c1.buildSessionFactory();

}

public static Session getSession()

{

return sssionFactory.openSession();

}

}

entity Gender.java

package com.lara.entity;

 

import javax.persistence.Entity;

import javax.persistence.Id;

import javax.persistence.Table;

 

@Entity

@Table(name="GENDER")

public class Gender

{

@Id

private Integer id;

private String name;

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

 

}

entity Education.java

package com.lara.entity;

 

import javax.persistence.Entity;

import javax.persistence.Id;

import javax.persistence.Table;

 

@Entity

@Table(name="EDUCATION")

public class Education

{

@Id

private Integer id;

private String name;

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

}

entity Address.java

package com.lara.entity;

 

import javax.persistence.CascadeType;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.Id;

import javax.persistence.OneToOne;

import javax.persistence.PrimaryKeyJoinColumn;

import javax.persistence.Table;

 

import org.hibernate.annotations.GenericGenerator;

import org.hibernate.annotations.Parameter;

 

@Entity

@Table(name="ADDRESS")

@GenericGenerator(name="gen",

strategy="foreign",

parameters=@Parameter(name="property",

value="employee"))

public class Address {

@Id

@GeneratedValue(generator="gen")

private Integer id;

private String houseNo;

private String streetName;

@OneToOne(cascade=CascadeType.ALL)

@PrimaryKeyJoinColumn

private Employee employee;

public Employee getEmployee() {

return employee;

}

public void setEmployee(Employee employee) {

this.employee = employee;

}

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public String getHouseNo() {

return houseNo;

}

public void setHouseNo(String houseNo) {

this.houseNo = houseNo;

}

public String getStreetName() {

return streetName;

}

public void setStreetName(String streetName) {

this.streetName = streetName;

}

}

entity Employee.java

package com.lara.entity;

 

import java.util.HashSet;

import java.util.Set;

 

import javax.persistence.CascadeType;

import javax.persistence.Entity;

import javax.persistence.Id;

import javax.persistence.JoinColumn;

import javax.persistence.JoinTable;

import javax.persistence.ManyToMany;

import javax.persistence.ManyToOne;

import javax.persistence.OneToOne;

import javax.persistence.Table;

 

@Entity

@Table(name="EMPLOYEE")

public class Employee {

@Id

private Integer id;

private String firstName;

private String lastName;

@OneToOne(cascade=CascadeType.ALL)

private Address address;

@ManyToOne

@JoinColumn(name = "gender_id")

private Gender gender;

@ManyToOne

@JoinColumn(name = "education_id")

private Education education;

@ManyToMany(cascade=CascadeType.ALL)

@JoinTable(name="EMPLOYEE_SKILL",

joinColumns={@JoinColumn(name="EMP_ID")},

inverseJoinColumns={@JoinColumn(name="SKILL_ID")})

private Set<Skill> skills = new HashSet<Skill>();

public Set<Skill> getSkills() {

return skills;

}

public void setSkills(Set<Skill> skills) {

this.skills = skills;

}

public Address getAddress() {

return address;

}

public void setAddress(Address address) {

this.address = address;

}

public Gender getGender() {

return gender;

}

public void setGender(Gender gender) {

this.gender = gender;

}

public Education getEducation() {

return education;

}

public void setEducation(Education education) {

this.education = education;

}

 

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public String getFirstName() {

return firstName;

}

public void setFirstName(String firstName) {

this.firstName = firstName;

}

public String getLastName() {

return lastName;

}

public void setLastName(String lastName) {

this.lastName = lastName;

}

}

entity Skill.java

package com.lara.entity;

 

import javax.persistence.Entity;

import javax.persistence.Id;

import javax.persistence.Table;

 

@Entity

@Table(name="SKILL")

public class Skill

{

@Id

private Integer id;

private String name;

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

}

dao GenderDAO.java

package com.lara.dao;

 

import java.util.List;

 

import com.lara.entity.Gender;

import com.lara.util.HibernateUtil;

 

public class GenderDAO

{

public static List<Gender> readGenders()

{

return (List<Gender>) HibernateUtil.getSession().createCriteria(Gender.class).list();

}

}

 

dao EducationDAO.java

package com.lara.dao;

 

import java.util.List;

 

import com.lara.entity.Education;

import com.lara.util.HibernateUtil;

 

public class EducationDAO

{

public static List<Education> readEducations()

{

return (List<Education>) HibernateUtil.getSession().createCriteria(Education.class).list();

}

}

dao SkillDAO.java

package com.lara.dao;

 

import java.util.List;

 

import com.lara.entity.Education;

import com.lara.entity.Skill;

import com.lara.util.HibernateUtil;

 

public class SkillDAO

{

public static List<Skill> readSkills()

{

return (List<Skill>) HibernateUtil.getSession().createCriteria(Skill.class).list();

}

}

 

dao EmployeeDAO.java

package com.lara.dao;

 

import org.hibernate.Session;

 

import com.lara.entity.Employee;

import com.lara.util.HibernateUtil;

 

public class EmployeeDAO {

public static Integer save(Employee emp)

{

Integer id = null;

Session session = HibernateUtil.getSession();

session.beginTransaction();

id = (Integer)session.save(emp);

session.getTransaction().commit();

return id;

}

}

test Manager.java

package com.lara.test;

 

import java.util.HashSet;

import java.util.List;

import java.util.Set;

 

import org.hibernate.Session;

 

import com.lara.dao.EducationDAO;

import com.lara.dao.EmployeeDAO;

import com.lara.dao.GenderDAO;

import com.lara.dao.SkillDAO;

import com.lara.entity.Address;

import com.lara.entity.Education;

import com.lara.entity.Employee;

import com.lara.entity.Gender;

import com.lara.entity.Skill;

import com.lara.util.HibernateUtil;

 

public class Manager

{

public static void main(String[] args)

{

/*

List<Gender> genders = GenderDAO.readGenders();

List<Education> educations = EducationDAO.readEducations();

List<Skill> skills = SkillDAO.readSkills();

for(Gender g1 : genders)

{

System.out.println(g1.getId() + ":" + g1.getName());

}

*/

Employee emp = new Employee();

emp.setId(101);

emp.setFirstName("abc");

emp.setLastName("xyz");

Gender g1 = new Gender();

g1.setId(1);

Education e1 = new Education();

e1.setId(2);

Set<Skill> skills = new HashSet<>();

Skill s1 = new Skill();

s1.setId(1);

Skill s2 = new Skill();

s2.setId(2);

skills.add(s1);

skills.add(s2);

Address a1 = new Address();

a1.setHouseNo("123");

a1.setStreetName("btm");

emp.setGender(g1);

emp.setEducation(e1);

emp.setSkills(skills);

emp.setAddress(a1);

a1.setEmployee(emp);

EmployeeDAO.save(emp);

}

}

servlets SaveEmployeeServlet.java

package com.lara.servlets;

 

import java.io.IOException;

import java.io.PrintWriter;

import java.util.HashSet;

import java.util.List;

import java.util.Set;

 

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

import com.lara.dao.EducationDAO;

import com.lara.dao.EmployeeDAO;

import com.lara.dao.GenderDAO;

import com.lara.dao.SkillDAO;

import com.lara.entity.Address;

import com.lara.entity.Education;

import com.lara.entity.Employee;

import com.lara.entity.Gender;

import com.lara.entity.Skill;

 

/**

* Servlet implementation class SaveEmployeeServlet

*/

public class SaveEmployeeServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

/**

* @see HttpServlet#HttpServlet()

*/

public SaveEmployeeServlet() {

super();

// TODO Auto-generated constructor stub

}

 

/**

* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

*/

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

List<Gender> genders = GenderDAO.readGenders();

List<Education> educations = EducationDAO.readEducations();

List<Skill> skills = SkillDAO.readSkills();

request.setAttribute("genders", genders);

request.setAttribute("educations", educations);

request.setAttribute("skills", skills);

request.getRequestDispatcher("newEmp.jsp").forward(request, response);

}

 

/**

* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)

*/

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

String id = request.getParameter("id");

String firstName = request.getParameter("firstName");

String lastName = request.getParameter("lastName");

String houseNo = request.getParameter("houseNo");

String streetName = request.getParameter("streetName");

String gender = request.getParameter("gender");

String education = request.getParameter("education");

String[] skills = request.getParameterValues("skills");

Address address = new Address();

address.setHouseNo(houseNo);

address.setStreetName(streetName);

Employee employee = new Employee();

employee.setId(Integer.parseInt(id));

employee.setFirstName(firstName);

employee.setLastName(lastName);

employee.setAddress(address);

address.setEmployee(employee);

Gender genderObj = new Gender();

genderObj.setId(Integer.parseInt(gender));

employee.setGender(genderObj);

Education educationObj = new Education();

educationObj.setId(Integer.parseInt(education));

employee.setEducation(educationObj);

Set<Skill> allSkills = new HashSet<>();

Skill skillObj;

for(String skill : skills)

{

skillObj = new Skill();

skillObj.setId(Integer.parseInt(skill));

allSkills.add(skillObj);

}

employee.setSkills(allSkills);

Integer status = EmployeeDAO.save(employee);

PrintWriter out = response.getWriter();

out.println(id + " saved in the database");

}

 

}

hibernate.cfg.xml

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

 

<hibernate-configuration>

<session-factory>

<property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>

<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>

<property name="hibernate.connection.username">system</property>

<property name="hibernate.connection.password">great123</property>

<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>

<property name="hibernate.hbm2ddl.auto">update</property>

<property name="hibernate.show_sql">true</property>

<mapping class="com.lara.entity.Gender"/>

<mapping class="com.lara.entity.Education"/>

<mapping class="com.lara.entity.Skill"/>

<mapping class="com.lara.entity.Address"/>

<mapping class="com.lara.entity.Employee"/>

</session-factory>

</hibernate-configuration>