整合开发环境
创建Spring的配置文件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.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<!-- 导入资源文件 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 配置 C3P0 数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.user}"></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.initPoolSize}"></property>
<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
</bean>
<!-- 配置 SessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
<property name="mappingLocations" value="classpath:com/yang/ssh/entity/*.hbm.xml"></property>
</bean>
<!-- 配置 Spring 的声明式事务 -->
<!-- 1. 配置 hibernate 的事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 2. 配置事务属性 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="get*" read-only="true"/>
<tx:method name="lastNameIsValid" read-only="true"/>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<!-- 3. 配置事务切入点, 再把事务属性和事务切入点关联起来 -->
<aop:config>
<aop:pointcut expression="execution(* com.yang.ssh.service.*.*(..))" id="txPointcut"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>
</beans>
创建hibernate的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 配置 hibernate 的基本属性 -->
<!-- 方言 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<!-- 是否显示及格式化 SQL -->
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<!-- 生成数据表的策略 -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 二级缓存相关 -->
</session-factory>
</hibernate-configuration>
db.properties配置文件
jdbc.user=root
jdbc.password=root
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql:///spring6
jdbc.initPoolSize=5
jdbc.maxPoolSize=10
#...
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.yang.ssh.dao.EmployeeDao">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="departmentDao" class="com.yang.ssh.dao.DepartmentDao">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="employeeService" class="com.yang.ssh.service.EmployeeService">
<property name="employeeDao" ref="employeeDao"></property>
</bean>
<bean id="departmentService" class="com.yang.ssh.service.DepartmentService">
<property name="departmentDao" ref="departmentDao"></property>
</bean>
<bean id="employeeAction" class="com.yang.ssh.actions.EmployeeAction"
scope="prototype">
<property name="employeeService" ref="employeeService"></property>
<property name="departmentService" ref="departmentService"></property>
</bean>
</beans>
实体类
package com.yang.ssh.entity;
import java.util.Date;
public class Employee {
private Integer id;
// 不能被修改
private String lastName;
private String email;
// 从前端传入的是 String 类型, 所以需要注意转换
private Date birth;
// 不能被修改
private Date createTime;
// 单向 n-1 的关联关系
private Department department;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
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;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
@Override
public String toString() {
return "Employee [id=" + id + ", lastName=" + lastName + ", email="
+ email + ", birth=" + birth + ", createTime=" + createTime
+ ", department=" + department + "]";
}
}
dao
baseDao
package com.yang.ssh.dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
public class BaseDao {
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public Session getSession(){
return this.sessionFactory.getCurrentSession();
}
}
package com.yang.ssh.dao;
import java.util.List;
import com.yang.ssh.entity.Employee;
import org.hibernate.Query;
public class EmployeeDao extends BaseDao{
public void delete(Integer id){
String hql = "DELETE FROM Employee e WHERE e.id = ?";
getSession().createQuery(hql).setInteger(0, id).executeUpdate();
}
public List<Employee> getAll(){
String hql = "FROM Employee e LEFT OUTER JOIN FETCH e.department";
return getSession().createQuery(hql).list();
}
public void saveOrUpdate(Employee employee){
getSession().saveOrUpdate(employee);
}
public Employee getEmployeeByLastName(String lastName){
String hql = "FROM Employee e WHERE e.lastName = ?";
Query query = getSession().createQuery(hql).setString(0, lastName);
Employee employee = (Employee) query.uniqueResult();
System.out.println(employee.getDepartment().getClass().getName());
return employee;
}
public Employee get(Integer id){
return (Employee) getSession().get(Employee.class, id);
}
}
service
package com.yang.ssh.service;
import com.yang.ssh.dao.EmployeeDao;
import com.yang.ssh.entity.Employee;
import java.util.List;
public class EmployeeService {
private EmployeeDao employeeDao;
public void setEmployeeDao(EmployeeDao employeeDao) {
this.employeeDao = employeeDao;
}
public boolean lastNameIsValid(String lastName){
return employeeDao.getEmployeeByLastName(lastName) == null;
}
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();
// employees.clear();
return employees;
}
public Employee get(Integer id) {
return employeeDao.get(id);
}
}
controller
package com.yang.ssh.actions;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map;
import com.yang.ssh.entity.Employee;
import com.yang.ssh.service.DepartmentService;
import com.yang.ssh.service.EmployeeService;
import org.apache.struts2.interceptor.RequestAware;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;
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(DepartmentService 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;
}
private InputStream inputStream;
public InputStream getInputStream() {
return inputStream;
}
public String delete() {
try {
employeeService.delete(id);
inputStream = new ByteArrayInputStream("1".getBytes("UTF-8"));
} catch (Exception e) {
e.printStackTrace();
try {
inputStream = new ByteArrayInputStream("0".getBytes("UTF-8"));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
}
return "ajax-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);
return SUCCESS;
}
/**
* 可以根据 id 来判断为 save 方法准备的 model 是 new 的还是从数据库获取的!
*/
public void prepareSave(){
if(id == null){
model = new Employee();
}else{
model = employeeService.get(id);
}
}
private String lastName;
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String validateLastName() throws UnsupportedEncodingException{
if(employeeService.lastNameIsValid(lastName)){
inputStream = new ByteArrayInputStream("1".getBytes("UTF-8"));
}else{
inputStream = new ByteArrayInputStream("0".getBytes("UTF-8"));
}
return "ajax-success";
}
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;
}
}