Hibernate 实现 CRUD(附项目源码)
<?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>
<property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
<property name="hibernate.connection.driverClass">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.username">mine</property>
<property name="hibernate.connection.password">mine</property>
<property name="hibernate.connection.jdbcUrl">jdbc:oracle:thin:@127.0.0.1:1521:orcl</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping resource="com/ssh/entities/Department.hbm.xml"/>
<mapping resource="com/ssh/entities/Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<context:property-placeholder location="classpath:db.properties" ignore-unresolvable="true"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="initialPoolSize" value="${jdbc.initialPoolSize}"></property>
<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingResources">
<list>
<value>com/ssh/entities/Department.hbm.xml</value>
<value>com/ssh/entities/Employee.hbm.xml</value>
<value>hibernate.cfg.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.OracleDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean>
<!-- 配置 spring 的声明式事务
1.配置 hibernate 的事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"></bean>
2.配置事务属性
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:method name="get" read-only="true"/>
<tx:method name="*"/>
</tx:attributes>
</tx:advice> -->
<!-- aop:config
<aop:pointcut expression="execution(* com.guor.ssh.service..(..))" id="txPointcut"/>
<aop:advisor advice-ref="exAdvice" pointcut-ref="txPointcut"/>
</aop:config> -->
</beans>
applicationContext-beans.xml?
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="employeeDao" class="com.ssh.dao.EmployeeDao">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="departmentDao" class="com.ssh.dao.DepartmentDao">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="employeeService" class="com.ssh.service.EmployeeService">
<property name="employeeDao" ref="employeeDao"></property>
</bean>
<bean id="departmentService" class="com.ssh.service.DepartmentService">
<property name="departmentDao" ref="departmentDao"></property>
</bean>
<bean id="employeeAction" class="com.ssh.actions.EmployeeAction" scope="prototype">
<property name="employeeService" ref="employeeService"></property>
<property name="departmentService" ref="departmentService"></property>
</bean>
</beans>
struts.xml?
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" />
<package name="default" namespace="/" extends="struts-default">
<interceptors>
<interceptor-stack name="sshStack">
<interceptor-ref name="paramsPrepareParamsStack">
<param name="prepare.alwaysInvokePrepare">false</param>
</interceptor-ref>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="sshStack"></default-interceptor-ref>
<action name="emp-*" class="employeeAction" method="{1}">
<result name="list">/WEB-INF/views/emp-list.jsp</result>
<result type="stream" name="delete">
<param name="contentType">text/html</param>
<param name="inputName">inputStream</param>
</result>
<result name="input">/WEB-INF/views/emp-input.jsp</result>
<result name="success" type="redirect">/emp-list</result>
</action>
</package>
</struts>
3、类文件
EmployeeAction
package com.ssh.actions;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map;
import org.apache.struts2.interceptor.RequestAware;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;
import com.ssh.entities.Employee;
import com.ssh.service.DepartmentService;
import com.ssh.service.EmployeeService;
public class EmployeeAction extends ActionSupport implements RequestAware,
ModelDriven<Employee>,Preparable{
private static final long serialVersionUID = 1L;
private EmployeeService employeeService;
public void setEmployeeService(EmployeeService employeeService) {
this.employeeService = employeeService;
}
private DepartmentService departmentService;
public void setDepartmentService(Depart 《一线大厂 Java 面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》无偿开源 威信搜索公众号【编程进阶路】 mentService departmentService) {
this.departmentService = departmentService;
}
public String list() {
request.put("employees",employeeService.getAll());
return "list";
}
private Integer id;
public void setId(Integer id) {
this.id = id;
}
public InputStream inputStream;
public InputStream getInputStream() {
return inputStream;
}
public String delete() {
try {
employeeService.delete(id);
inputStream = new ByteArrayInputStream("1".getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return SUCCESS;
}
public String input() {
request.put("departments", departmentService.getAll());
return INPUT;
}
public void prepareInput() {
if(id!=null) {
model = employeeService.get(id);
}
}
public String save() {
if(id == null) {
model.setCreateTime(new Date());
}
employeeService.saveOrUpdate(model);
System.out.println("model");
return SUCCESS;
}
public void prepareSave() {
if(id == null) {
model = new Employee();
}else {
model = employeeService.get(id);
}
}
private Map<String,Object> request;
@Override
public void setRequest(Map<String, Object> arg0) {
this.request = arg0;
}
@Override
public void prepare() throws Exception {}
private Employee model;
@Override
public Employee getModel() {
return model;
}
}
EmployeeService
package com.ssh.service;
import java.util.List;
import com.ssh.dao.EmployeeDao;
import com.ssh.entities.Employee;
public class EmployeeService {
private EmployeeDao employeeDao;
public void setEmployeeDao(EmployeeDao employeeDao) {
this.employeeDao = employeeDao;
}
public void saveOrUpdate(Employee employee) {
employeeDao.saveOrUpdate(employee);
}
public void delete(Integer id) {
employeeDao.delete(id);
}
public List<Employee> getAll(){
List<Employee> employees = employeeDao.getAll();
return employees;
}
public Employee get(Integer id) {
return employeeDao.get(id);
}
}
EmployeeDao?
package com.ssh.dao;
import java.util.List;
import com.ssh.entities.Employee;
public class EmployeeDao extends BaseDao{
public void delete(Integer id) {
String hql = "DELETE From Employee e where e.id=?0";
getSession().createQuery(hql).setParameter(0,id).executeUpdate();
}
public List<Employee> getAll() {
//String hql = "From Employee e LEFT OUTER JOIN FETCH e.department";
String hql = "From Employee";
return getSession().createQuery(hql).list();
}
public void saveOrUpdate(Employee employee) {
getSession().saveOrUpdate(employee);
}
public Employee get(Integer id) {
return (Employee)getSession().get(Employee.class,id);
}
}
emp-list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src = "js/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
$(function(){
$(".delete").click(function(){
var lastName = $(this).next(":input").val();
var flag = confirm("确定要删除"+lastName+"的信息吗?");
if(flag){
var (this).parent().parent();
var url = this.href;
var args = {"time":new Date()}
$.post(url,args,function(data){
if(data=="1"){
alert("删除成功!");
$tr.remove();
}else{
alert("删除失败!");
}
});
}
return false;
})
})
</script>
</head>
<body>
<h4>Employee List Page</h4>
<s:if test="#request.employees == null||#request.employees.size() == 0">
没有任何员工信息
</s:if>
<s:else>
<table border="1" cellpadding="10" cellspacing="0">
<tr>
<td>ID</td>
<td>LASTNAME</td>
<td>EMAIL</td>
<td>BIRTH</td>
<td>CREATETIME</td>
<td>delete</td>
<td>edit</td>
</tr>
<s:iterator value="#request.employees">
<tr>
<td>${id }</td>
<td>${lastName }</td>
<td>${email }</td>
<td>${birth }</td>
<td>${createTime }</td>
<td>
<a href="emp-delete?id=${id } " class="delete">Delete</a>
<input type="hidden" value="${lastName }"/>
</td>
<td><a href="emp-input?id=${id }">Edit</a></td>
</tr>
</s:iterator>
</table>
</s:else>
</body>
</html>
emp-input.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h4>Employee Input Page</h4>
<s:form action="emp-save" method="post">
<s:if test="id != null">
<s:textfield name="lastName" label="LastName" disabled="true"></s:textfield>
<s:hidden name="id"></s:hidden>
</s:if>
<s:else>
评论