lundi 13 avril 2015

How do I integrate my Spring project with Hibernate

I have done a small Employee project using Springs. This project helps to add,edit,delete the employee in the database. I had used normal JDBC for the database connection. Now I want to integrate Hibernate into my project. Please help me. I m learning hibernate and I trying something out of it.


This is my employee controller.



package com.employee.controller;




import java.sql.SQLException;
import java.util.ArrayList;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.employee.dao.EmployeeDAO;
import com.employee.model.Employee;

@Controller
public class EmployeeController {

@Autowired
EmployeeDAO employeeDao;

@RequestMapping(value = "/employee", method = RequestMethod.GET)
public ModelAndView employee() {
return new ModelAndView("registration", "command", new Employee());
}
/* @RequestMapping(value = "/*", method = RequestMethod.GET)
public ModelAndView employeef() {
return new ModelAndView("registration", "command", new EmployeeMaster());
}
*/

@RequestMapping(value = "/addemployee", method = RequestMethod.POST)
public String addEmployee(@ModelAttribute Employee employee/*, ModelMap model*/) {
try {
employeeDao.create(employee.getFirstName(), employee.getEmailId(), employee.getAge());
return "1";


}catch(Exception e) {
return "2";

}

}

@RequestMapping("/ViewEmployeeDetails")
public String FetchEmployeeDetails(@ModelAttribute Employee employee,ModelMap map,HttpSession session) throws SQLException {

System.out.println("Inside FetchEmployye details");
Employee e=new Employee();
ArrayList<Employee> xx=new ArrayList<Employee>();
xx=employeeDao.listEmployee();
System.out.println("Prinitgn List Size..!!! "+xx.size());
map.addAttribute("EmpDetails", xx);
session.setAttribute("EmpDetails", xx);
return "viewnew";
}

@RequestMapping("/EditUserDEtails")
public String EditUserDEtails(@ModelAttribute/*("UserEditDetails")*/ Employee employee,ModelMap map,HttpSession session,HttpServletRequest req)
{
System.out.println("Inside EditUserDEtails");

String Id=req.getParameter("empId");

int val=Integer.parseInt(Id);

System.out.println("Employee ID is..!! "+Id);
ArrayList<Employee> xx=new ArrayList<Employee>();


xx=(ArrayList<Employee>) session.getAttribute("EmpDetails");

System.out.println("Prinitng XXX Size..!!!" +xx);

ArrayList<Employee> Newxx=new ArrayList<Employee>();

Employee e1=new Employee();

for (int i = 0; i < xx.size(); i++) {

if(val==xx.get(i).getEmpId())
{
e1.setAge(xx.get(i).getAge());
e1.setEmailId(xx.get(i).getEmailId());
e1.setEmpId(xx.get(i).getEmpId());
e1.setFirstName(xx.get(i).getFirstName());
Newxx.add(e1);
}
}
System.out.println("hhhh:"+e1.getFirstName());
map.put("UserEditDetails", e1);
// map.put("yyy",Newxx);
return "edit";
}

@RequestMapping(value = "/view", method = RequestMethod.GET)
public ModelAndView view() {
return new ModelAndView("view", "command", new Employee());
}

@RequestMapping(value="/viewemployee")
public String viewEmployee() {
return "viewnew";
}

/* @RequestMapping(value="/viewemployee")
public String viewEmployee(@RequestParam int id, ModelMap model) {

Employee employee = new Employee();
ModelMap model = new ModelMap();
// List<Employee> employees = new ArrayList<Employee>();
try {

employee = employeeDao.getEmployee(id);
model.addAttribute("name", employee.getFirstName());
model.addAttribute("age", employee.getAge());
model.addAttribute("id", employee.getEmpId());
model.addAttribute("email", employee.getEmailId());



return "result";
employees = employeeDao.listEmployee();
return employees;

}catch(Exception e) {

}
return "2";
}*/

@RequestMapping(value = "/edit", method = RequestMethod.GET)
public ModelAndView edit() {

return new ModelAndView("edit", "command", new Employee());
}

@RequestMapping(value="/editemployee" ,method=RequestMethod.POST)
public String editEmployee(@ModelAttribute Employee employee/*@RequestParam int id, @RequestParam String firstName, @RequestParam String emailId, @RequestParam int age*/){

try {

int id = employee.getEmpId();
String firstName = employee.getFirstName();
String emailId = employee.getEmailId();
int age = employee.getAge();
/*int id=1;
String firstName="nitesh";
String emailId="nitesh";
int age=25;*/


String check= employeeDao.update(id, firstName, emailId, age);
if (check=="1") {
return "1";
}else {
return "2";
}

}catch(Exception e) {
return "2";
}

}

@RequestMapping(value = "/delete", method = RequestMethod.GET)
public ModelAndView delete() {
return new ModelAndView("delete", "command", new Employee());
}

@RequestMapping(value="/deleteemployee")
public String deleteEmployee(@ModelAttribute Employee employee) {
try {
int id = employee.getEmpId();

String check =employeeDao.delete(id);
if (check=="1") {
return "1";
}
}catch(Exception e) {
return "2";
}
return "2";


}

}


This is my dao impl



package com.employee.dao.impl;


import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;












import org.springframework.jdbc.core.JdbcTemplate;

import com.employee.dao.EmployeeDAO;
import com.employee.mapping.EmployeeMapper;
import com.employee.model.Employee;
import com.sun.org.apache.bcel.internal.generic.Select;

public class EmployeeDaoImpl implements EmployeeDAO{
private DataSource dateSource;
private JdbcTemplate jdbcTemplateObject;

@Override
public void setDataSource(DataSource dataSource) {
this.dateSource = dataSource;
this.jdbcTemplateObject = new JdbcTemplate(dataSource);

}

public void create(String firstName, String emailId, Integer age) {
String SQL = "insert into Employee (firstName, emailId, age) values (?, ?, ?)";

jdbcTemplateObject.update(SQL,firstName,emailId,age);
System.out.println("Created Record Name = " + firstName + " Age = " + age);
return;
}

@Override
public Employee getEmployee(Integer id) throws SQLException {
System.out.println("Creating statement...");
Employee emp = new Employee();
Connection con = dateSource.getConnection();
System.out.println("connection done");

String SQL = "select * from Employee where empId= "+id;
Statement stmt = con.createStatement();

ResultSet rs = stmt.executeQuery(SQL);

while(rs.next()){
//Retrieve by column name

emp.setEmpId(rs.getInt("empId"));

emp.setFirstName(rs.getString("firstName"));
emp.setEmailId(rs.getString("emailId"));
emp.setAge(rs.getInt("age"));

return emp;
}
rs.close();
con.close();
return null;
}

@Override
public ArrayList<Employee> listEmployee() throws SQLException {

System.out.println("Creating statement...");
List<Employee> emp = new ArrayList<Employee>();
Employee emp1 =null;
Connection con = dateSource.getConnection();
System.out.println("connection done");

String SQL = "select * from Employee";
Statement stmt = con.createStatement();

//ResultSet rs = stmt.execute(SQL);
ResultSet rs = stmt.executeQuery(SQL);
// ResultSet rs=stmt.getResultSet();

System.out.println("XXXXXXXXX :"+rs.toString());

while(rs.next()){
//Retrieve by column name
emp1=new Employee();
System.out.println("Getting values in result Set..!!!");
emp1.setEmpId(rs.getInt("empId"));
emp1.setFirstName(rs.getString("firstName"));
emp1.setEmailId(rs.getString("emailId"));
emp1.setAge(rs.getInt("age"));
emp.add(emp1);


}
rs.close();
con.close();
return (ArrayList<Employee>) emp;


}

@Override
public String delete(Integer id) throws SQLException {
/*String SQL = "delete from Employee where id = ?";
jdbcTemplateObject.update(SQL, id);
System.out.println("Deleted Record with ID = " + id );
return;*/
Employee emp = new Employee();
System.out.println("deleting the connetion ");
Connection con = dateSource.getConnection();
System.out.println("connection establised");
Statement stmt = con.createStatement();

String sql1 = "select * from Employee where empId="+id;
ResultSet rs = stmt.executeQuery(sql1);
while(rs.next()) {
emp.setEmpId(rs.getInt("empId"));
}
if(emp.getEmpId() == 0) {
return "2";
}else {
String SQL = "delete from Employee where empId="+id;
stmt.executeUpdate(SQL);
System.out.println("deleted");
return "1";
}

}

@Override
public String update(Integer id, String firstName, String emailId, Integer age) throws SQLException {
/* String SQL = "update employee set age = ? set firstName= ? setemailId=? where id = ?";
jdbcTemplateObject.update(SQL, firstName,emailId,age, id);
System.out.println("Updated Record with ID = " + id );
return;*/
Employee emp = new Employee();
System.out.println("editing the connection ");
Connection con = dateSource.getConnection();
System.out.println("connection establised");
Statement stmt = con.createStatement();
String sql1 = "select * from Employee where empId="+id;
ResultSet rs = stmt.executeQuery(sql1);
while(rs.next()) {
emp.setEmpId(rs.getInt("empId"));
}
if(emp.getEmpId()==0) {
return "2";
}else {

String SQL = "update Employee set firstName='"+firstName+"', emailId = '"+emailId +"', age ='"+age+"' where empId="+id;
stmt.executeUpdate(SQL);
System.out.println("updated");
return "1";
}
}
/*public Employee check(Integer id) throws SQLException {



System.out.println("Creating statement...");
Employee emp = new Employee();
Connection con = dateSource.getConnection();
System.out.println("connection done");

String SQL = "select empId from Employee where empId= "+id;
Statement stmt = con.createStatement();

ResultSet rs = stmt.executeQuery(SQL);

while(rs.next()){
//Retrieve by column name

emp.setEmpId(rs.getInt("empId"));
return emp;

}
return emp;
}
*/

@Override
public Employee check(Integer id) throws SQLException {
// TODO Auto-generated method stub
return null;
}

@Override
public Employee fetchEmployeeDetails() {
// TODO Auto-generated method stub
return null;
}
}


This is my employee mapper



package com.employee.mapping;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;

import com.employee.model.Employee;
public class EmployeeMapper implements RowMapper<Employee> {



public Employee mapRow(ResultSet rs, int rowNum) throws SQLException {
Employee emp = new Employee();
emp.setEmpId( rs.getInt("id"));
emp.setFirstName(rs.getString("name"));
emp.setAge(rs.getInt("age"));
/* emp.setEmailId(rs.getString("emailId"));*/
return emp;

}
}


This is my employee model



package com.employee.model;

import java.io.Serializable;

public class Employee implements Serializable{

private int empId;
private String firstName;

private int age;
private String emailId;


public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
@Override
public String toString() {
return "Employee [empId=" + empId + ", firstName=" + firstName
+ ", age=" + age + ", emailId=" + emailId + "]";
}


}


**This is my Spring-servlet.xml**

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

<context:component-scan base-package="com.employee.controller" />
<context:annotation-config/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<mvc:annotation-driven></mvc:annotation-driven>


<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
<property name="url" value="jdbc:http://sqlserver127.0.0.1:1433;databasename=Employee"/>
<property name="username" value="sa"/>
<property name="password" value="r@1234"/>

</bean>


<bean id="employeedaoimpl"
class="com.employee.dao.impl.EmployeeDaoImpl">
<property name="dataSource" ref="dataSource" />
</bean>

<!-- <jee:jndi-lookup jndi-name="java:/Employee" id="employee"></jee:jndi-lookup> -->



</beans>


This is my Hibernate.cfg.xml



<?xml version='1.0' encoding='utf-8'?>
<!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>

<!-- Database connection settings -->
<property name="connection.driver_class">com.microsoft.jdbc.sqlserver.SQLServerDriver</property>
<property name="connection.url">jdbc:http://sqlserverlocalhost:1433;databaseName=Employee</property>
<property name="connection.username">sa</property>
<property name="connection.password">r@1234</property>

<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>

<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>

<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>

<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>

<!-- Names the annotated entity class -->
<mapping class="com.employee.model.Employee"/>

</session-factory>

</hibernate-configuration>


These are my views registration view



<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>

<h2>Employee Information</h2>
<form:form method="POST" action="/EmployeeDemo/addemployee">
<table>
<tr>
<td><form:label path="firstName">Name</form:label></td>
<td><form:input path="firstName" /></td>
</tr>
<%-- <tr>

<td><form:label path="empId">id</form:label></td>
<td><form:input path="empId" /></td>
</tr> --%>
<tr>
<td><form:label path="emailId">emailid</form:label></td>
<td><form:input path="emailId" /></td>
</tr>
<tr>
<td><form:label path="age">Age</form:label></td>
<td><form:input path="age" /></td>
</tr>

<tr>
<td colspan="2">
<input type="submit" value="Submit"/>
</td>
</tr>


</table>
</form:form>

</body>
</html>


this is my view all employee view



<%@ page import="java.io.*,java.util.*,java.sql.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>


<html>
<head>
<title>SELECT Operation</title>
</head>
<body>

<!-- <sql:setDataSource var="snapshot" driver="com.microsoft.sqlserver.jdbc.SQLServerDriver"
url="jdbc:http://sqlserver127.0.0.1:1433;databasename=Employee"
user="sa" password="r@1234"/> -->

<%-- <sql:query dataSource="${snapshot}" var="result">
SELECT * from Employee;
</sql:query> --%>

<table border="1" width="100%">
<tr>
<th>Emp ID</th>
<th>First Name</th>
<th>Email Id</th>
<th>Age</th>
<th> edit </th>
</tr>
<c:forEach var="row" items="${EmpDetails}">
<tr>
<td><c:out value="${row.empId}"/></td>
<td><c:out value="${row.firstName}"/></td>
<td><c:out value="${row.emailId}"/></td>
<td><c:out value="${row.age}"/></td>


<td><a href="EditUserDEtails?empId=<c:out value="${row.empId}"/>">edit</a></td>

</tr>
</c:forEach>
</table>

</body>
</html>


this is my edit view



<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>

<h2>Employee Information</h2>

<form:form method="POST" action="/EmployeeDemo/editemployee" modelAttribute="UserEditDetails" >
<table>
<tr>
<td><form:label path="empId" >id</form:label></td>
<td><form:input path="empId" /></td>

</tr>
<tr>
<td><form:label path="firstName">Name</form:label></td>
<td><form:input path="firstName" /></td>
</tr>

<tr>
<td><form:label path="emailId">emailid</form:label></td>
<td><form:input path="emailId" /></td>
</tr>
<tr>
<td><form:label path="age">Age</form:label></td>
<td><form:input path="age" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit"/>
</td>
</tr>
<!--
<a href="..WEB-INF/jsp/view.jsp">click here to view all the employee details</a> -->

</table>
</form:form>

</body>
</html>


This is my delete view



<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>

<h2>Employee Information</h2>
<form:form method="POST" action="/EmployeeDemo/deleteemployee">
<table>
<tr>

<td><form:label path="empId">id</form:label></td>
<td><form:input path="empId" value="null" /></td>
</tr>


<tr>
<td colspan="2">
<input type="submit" value="Submit"/>
</td>
</tr>


</table>
</form:form>

</body>
</html>


please help me to integrate this project with hibernate


Aucun commentaire:

Enregistrer un commentaire