我使用Springs完成了一个小型Employee项目。 该项目有助于在数据库中添加,编辑和删除员工。 我曾经使用普通的JDBC进行数据库连接。 现在我想将Hibernate集成到我的项目中。请帮我。我正在学习休眠,我尝试了一些东西。
这是我的员工控制员。
package com.employee.controller;
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 = "/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");
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 = "/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";
}
}
这是我的道具
package com.employee.dao.impl;
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;
}
}
这是我的员工映射器
package com.employee.mapping;
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 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:sqlserver://127.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>
这是我的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:sqlserver://localhost: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>
请帮我将此项目与hibernate集成
答案 0 :(得分:0)
参考 - http://www.javabench.in/2012/04/spring-hibernate-integration.html