Struts2+Hibernate实现增、删、查、改的简单网页(连接数据库)



1、基本的环境
1.1、开发工具:Myeclipse 2017 CI
1.2、struts2:struts-2.3.34

Struts2+Hibernate实现增、删、查、改的简单网页(连接数据库)_第1张图片

1.3、hibernate:hibernate-release-5.2.10.Final

Struts2+Hibernate实现增、删、查、改的简单网页(连接数据库)_第2张图片

1.4、tomcat: apache-tomcat-8.5.15

1.5、mysql驱动:mysql-connector-java-5.1.42-bin
1.7、C3P0数据源

1.8、数据库MYSQL5.1以上

2、搭建基本strust2运行环境
2.1、配置web.xml



	
		Struts2
		org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
	
	
		Struts2
		/*
	

	
		index.jsp
	

2.2、在src目录下创建strust.xml文件(这个是最终的strust.xml)





	
	

	
	

		
			
				
					false
				
			
		

		
		
			emp-list
			/emp-{1}.jsp
		

		
			/success.jsp
		

	
3、用hibernate编写dao层
3.1、写一个Employee的javabean

package com.splend.crud.entity;

public class Employee {

	private Integer employeeId;
	private String firstName;
	private String lastName;
	private String email;

	public Employee() {
	}

	public Employee(Integer employeeId, String firstName, String lastName, String email) {
		super();
		this.employeeId = employeeId;
		this.firstName = firstName;
		this.lastName = lastName;
		this.email = email;
	}

	public Integer getEmployeeId() {
		return employeeId;
	}

	public void setEmployeeId(Integer employeeId) {
		this.employeeId = employeeId;
	}

	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;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}
}
3.2、在Employee.java类目录下创建Employee.hbm.xml




	
		
			
			
		

		
			
		

		
			
		

		
			
		
	
3.3、src目录下创建hibernate.cfg.xml文件




	
	
    
		splend
		1230
		com.mysql.jdbc.Driver
		jdbc:mysql://localhost:3306/sh

		
		
		org.hibernate.dialect.MySQL5InnoDBDialect

		
		true

		
		true

		
		update

		
		2

		
		true

		
		10
		5
		2

		2000
		2000

		
		10
		
		
		100

		
		30
		

		

	
3.4、编写BaseDao的泛型接口

package com.splend.crud.dao;

import java.util.List;

public interface BaseDao {

	T get(T entity);

	/**
	 * 获取全部列表
	 * 
	 * @return 所有T对象
	 */
	List getAll();

	/**
	 * 持久化实例
	 * @param entity
	 * @return 成功返回true,失败返回false
	 */
	boolean save(T entity);
	
	/**
	 * 更新一个T实例
	 * @param entity
	 * @return 更新成功返回True否则false
	 */
	boolean update(T entity);
	
	/**
	 * 删除T实例
	 * @param entity
	 * @return 成功返回true,失败false
	 */
	boolean delete(T entity);
	

}
3.5、EmployeeDao.java

package com.splend.crud.dao;

import com.splend.crud.entity.Employee;

public interface EmployeeDao extends BaseDao {

}
3.6、编写EmployeeDaoImpl实现类

package com.splend.crud.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

import com.splend.crud.entity.Employee;

public class EmployeeDaoImpl implements EmployeeDao {

	private SessionFactory sessionFactory;
	private Session session;
	private Transaction transaction;

	public EmployeeDaoImpl() {

		final StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build();
		try {
			sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
			session = sessionFactory.openSession();

		} catch (Exception e) {

			StandardServiceRegistryBuilder.destroy(registry);
			e.printStackTrace();
			System.out.println("EmployeeDaoImpl error");
		}finally {
			if (session != null) {
				session.close();
			}
		}
	}

	@Override
	public Employee get(Employee entity) {
		Employee employee = null;
		try {
			session = sessionFactory.openSession();
			transaction = session.beginTransaction();
			employee = session.find(Employee.class, entity.getEmployeeId());
			transaction.commit();
		} catch (Exception e) {
			if (transaction != null) {
				transaction.rollback();
			}
			employee = null;
			e.printStackTrace();
			System.out.println("public Employee get(Employee entity) error");
		}finally {
			if (session != null) {
				session.close();
			}
		}
		return employee;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List getAll() {

		List employees = null;

		try {
			session = sessionFactory.openSession();
			transaction = session.beginTransaction();
			employees = session.createQuery("FROM Employee").list();
			transaction.commit();
		} catch (Exception e) {
			if (transaction != null) {
				transaction.rollback();
			}
			employees = null;
			e.printStackTrace();
			System.out.println("public List getAll error");

		}finally {
			if (session != null) {
				session.close();
			}
		}
		return employees;
	}

	@Override
	public boolean save(Employee entity) {
		boolean result = false;
		try {
			session = sessionFactory.openSession();
			transaction = session.beginTransaction();
			session.save(entity);
			transaction.commit();
			result = true;
		} catch (Exception e) {
			if (transaction != null) {
				transaction.rollback();
			}
			result = false;
			e.printStackTrace();
			System.out.println("public boolean save(Employee entity) error");
		}finally {
			if (session != null) {
				session.close();
			}
		}
		return result;
	}

	@Override
	public boolean update(Employee entity) {
		boolean result = false;
		try {
			session = sessionFactory.openSession();
			transaction = session.beginTransaction();
			session.saveOrUpdate(entity);
			transaction.commit();
			result = true;
		} catch (Exception e) {
			if (transaction != null) {
				transaction.rollback();
			}
			result = false;
			e.printStackTrace();
			System.out.println("public boolean update(Employee entity) error");
		}finally {
			if (session != null) {
				session.close();
			}
		}
		return result;
	}

	@Override
	public boolean delete(Employee entity) {
		boolean result = false;
		try {
			session = sessionFactory.openSession();
			transaction = session.beginTransaction();
			session.delete(entity);
			transaction.commit();
			result = true;
		} catch (Exception e) {
			if (transaction != null) {
				transaction.rollback();
			}
			result = false;
			e.printStackTrace();
			System.out.println("public boolean delete(Employee entity) error");
		}finally {
			if (session != null) {
				session.close();
			}
		}
		return result;
	}

}
3.7 编写EmployeeService

package com.splend.crud.service;

import java.util.List;

import com.splend.crud.entity.Employee;

public interface EmployeeService {

	Employee get(Employee employee);

	List getEmployees();

	boolean save(Employee employee);

	boolean update(Employee employee);

	boolean delete(Employee employee);

}
3.8 编写EmployeeServiceImpl.java

package com.splend.crud.service;

import java.util.List;

import com.opensymphony.xwork2.inject.Inject;
import com.splend.crud.dao.EmployeeDao;
import com.splend.crud.entity.Employee;

public class EmployeeServiceImpl implements EmployeeService {

	@Inject(value="employeeDao",required=true)
	private EmployeeDao employeeDao;

	@Override
	public Employee get(Employee employee) {
		return employeeDao.get(employee);
	}

	@Override
	public List getEmployees() {
		return employeeDao.getAll();
	}

	@Override
	public boolean save(Employee employee) {
		return employeeDao.save(employee);
	}

	@Override
	public boolean update(Employee employee) {
		return employeeDao.update(employee);
	}

	@Override
	public boolean delete(Employee employee) {
		return employeeDao.delete(employee);
	}

}
4、编写Action以及相关jsp

package com.splend.crud.handler;

import java.util.Map;

import org.apache.struts2.interceptor.RequestAware;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;
import com.opensymphony.xwork2.inject.Inject;
import com.splend.crud.entity.Employee;
import com.splend.crud.service.EmployeeService;

public class EmployeeAction implements RequestAware, ModelDriven, Preparable {

	@Inject(value = "employeeService", required = true)
	private EmployeeService employeService;

	private Employee employee;

	public String edit() {
		return "edit";

	}

	public void prepareEdit() {
		Employee emp = new Employee();
		emp.setEmployeeId(employeeId);
		employee = employeService.get(emp);
	}

	public String update() {
		employeService.update(employee);
		return "success";
	}

	public void prepareUpdate() {
		employee = new Employee();
	}

	public String save() {
		employeService.save(employee);
		return "success";
	}

	public void prepareSave() {
		employee = new Employee();
	}

	public String delete() {
		Employee emp = new Employee();
		emp.setEmployeeId(employeeId);
		employeService.delete(emp);
		return "success";
	}

	public String list() {
		requset.put("emps", employeService.getEmployees());
		return "list";
	}

	private Map requset;

	private Integer employeeId;

	public void setEmployeeId(Integer employeeId) {
		this.employeeId = employeeId;
	}

	/**
	 * 获取Request对象的方式,这里选择实现RequestAware接口。
	 */
	@Override
	public void setRequest(Map request) {
		this.requset = request;
	}

	/**
	 * 使用ModelDriven把employee对象放到值栈栈顶。
	 */
	@Override
	public Employee getModel() {
		return employee;
	}

	@Override
	public void prepare() throws Exception {
		// TODO Auto-generated method stub
	}

}
4.1、写显示页面emp-list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>




Insert title here



	
	
		
		
		
		
	

	
				
ID FirstName LastName Email Edit Delete
${employeeId } ${firstName } ${lastName } ${email } Edit Delete
4.2、编写编辑页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>




Insert title here


	
		
		
		
		
		
	

4.3、主页index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>




Insert title here


	List All Employees


5、运行结果
5.1、运行index.jsp
Struts2+Hibernate实现增、删、查、改的简单网页(连接数据库)_第3张图片
5.2、List All Employees
Struts2+Hibernate实现增、删、查、改的简单网页(连接数据库)_第4张图片
5.3、Edit
Struts2+Hibernate实现增、删、查、改的简单网页(连接数据库)_第5张图片
6、总结
在学习了Hibernate后也没有进行怎么的运用,在这里学习Struts2后,也算是对学的进行简单的应用和总结一下
在运用的过程中也出现了一些问题,比如把hibernate的jar包没放在WEB-INF/lib下的话,就会显示tomcat的web应用
类加载器无法加载hibernate相关类,回想起之前看《深入理解Java虚拟机:JVM高级特性与最佳实践》的时候好像有
讲过一些类加载问题,然后把jar包放到WEB-INF/lib下就解决了这个问题。
如果这个其中有什么bug或者讲的不对的对方,请多多指教。
源代码下载:https://pan.baidu.com/s/1i6NrZYd


你可能感兴趣的:(JavaEE)