s2s4h5整合_spring

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ssh</groupId>
<artifactId>ssh</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>


<properties>
<!-- 统一源码的编码方式 -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- 统一各个框架版本 -->
<struts.version>2.5.10</struts.version>
<spring.version>4.3.8.RELEASE</spring.version>
</properties>

<dependencies>
<!-- ********************** Java Servlet API 4.0.0-b01 ********************** -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.0-b01</version>
<scope>provided</scope>
</dependency>

<!-- ********************** JUnit 4.12 ********************** -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>

<!-- ********************** Fastjson 1.2.7 ********************** -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.7</version>
</dependency>

<!-- ********************** AspectJ Weaver 1.8.7 ********************** -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.7</version>
</dependency>

<!-- ********************** Apache Log4j 1.2.17 ********************** -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>

<!-- ********************** Struts 2.3.24.1 ********************** -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.3.24.1</version>
<exclusions>
<exclusion>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-spring-plugin</artifactId>
<version>2.3.24.1</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-convention-plugin</artifactId>
<version>2.3.24.1</version>
</dependency>

<!-- ********************** Java Transaction API 1.1 ********************** -->
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
</dependency>

<!-- ********************** MySQL 5.1.38 ********************** -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>

<!-- ********************** Druid 1.0.16 ********************** -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.16</version>
</dependency>

<!-- ********************** Hibernate 5.0.6.Final ********************** -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.0.6.Final</version>
</dependency>

<!-- ********************** Spring 4.2.4.RELEASE ********************** -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>

</dependencies>

<build>
<plugins>
<!-- 统一源代码编译输出的JDK版本 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

applicationContext.xml

配置数据源,hibernate 的 sessionFactory

<?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" />

<!-- 扫描service自动注入为bean -->
<context:component-scan base-package="com.ssh" />

<!-- 配置数据源,使用的是alibaba的Druid数据源 -->
<bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<!-- 初始化连接大小 -->
<property name="initialSize" value="0" />
<!-- 连接池最大使用连接数量 -->
<property name="maxActive" value="20" />
<!-- 连接池最大空闲 -->
<property name="maxIdle" value="20" />
<!-- 连接池最小空闲 -->
<property name="minIdle" value="0" />
<!-- 获取连接最大等待时间 -->
<property name="maxWait" value="60000" />
<!-- <property name="poolPreparedStatements" value="true" /> <property
name="maxPoolPreparedStatementPerConnectionSize" value="33" /> -->
<property name="validationQuery" value="${validationQuery}" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<property name="testWhileIdle" value="true" />
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="25200000" />
<!-- 打开removeAbandoned功能 -->
<property name="removeAbandoned" value="true" />
<!-- 1800秒,也就是30分钟 -->
<property name="removeAbandonedTimeout" value="1800" />
<!-- 关闭abanded连接时输出错误日志 -->
<property name="logAbandoned" value="true" />
<!-- 监控数据库 -->
<!-- <property name="filters" value="stat" /> -->
<property name="filters" value="mergeStat" />
</bean>

<!-- 配置 SessionFactory -->
<!-- <bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.temp.use_jdbc_metadata_defaults">false</prop>
</props>
</property>
使用xml映射对象关系型数据库
<property name="mappingLocations" value="classpath:com/ssh/entities/*.hbm.xml"></property>
</bean> -->

<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!-- <property name="configLocation" value="classpath:hibernate.cfg.xml"></property> -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.temp.use_jdbc_metadata_defaults">false</prop>
</props>
</property>
<!-- 使用注解映射对象关系型数据库 -->
<property name="packagesToScan">
<list>
<!-- 可以加多个包 -->
<value>com.ssh.annotation.entities</value>
</list>
</property>
</bean>
</beans>


hibernate.cfg.xml配置,也可以整合到spring配置文件中,不用配置hibernate.cfg.xml


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 5.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-5.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

driverClassName=com.mysql.jdbc.Driver  
validationQuery=SELECT 1
jdbc.url=jdbc:mysql://localhost:3306/ssh
jdbc.username=root
jdbc.password=root


对象映射关系

1.xml 配置

package com.ssh.entities;

public class Department {
private Integer id;
private String departmentName;

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getDepartmentName() {
return departmentName;
}

public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}

}

Department.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class name="com.ssh.entities.Department" table="department">
<id name="id" type="java.lang.Integer">
<column name="ID" />
<generator class="native" />
</id>
<property name="departmentName" type="java.lang.String" >
<column name="DEPARTMENT_NAME" />
</property>
</class>
</hibernate-mapping>


package com.ssh.entities;

import java.util.Date;

public class Employee {
private Integer id;
private String lastName;

private String email;

private Date birth;
private Date createTime;

// 单向n-1
private Department dempartment;

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 getDempartment() {
return dempartment;
}

public void setDempartment(Department dempartment) {
this.dempartment = dempartment;
}

}
Employee.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.ssh.entities.Employee" table="employee">
<id name="id" type="java.lang.Integer">
<column name="ID" />
<generator class="native" />
</id>
<property name="lastName" type="java.lang.String" >
<column name="LAST_NAME"></column>
</property>
<property name="email" type="java.lang.String" >
<column name="EMAIL"></column>
</property>
<property name="birth" type="java.util.Date" >
<column name="BIRTH"></column>
</property>
<property name="createTime" type="java.util.Date" >
<column name="CREATE_TIME"></column>
</property>

<many-to-one name="dempartment" class="com.ssh.entities.Department">
<column name="DEPARTMENT_ID"></column>
</many-to-one>
</class>
</hibernate-mapping>

2.注解方式

package com.ssh.annotation.entities;


import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

@Entity//声明当前类为hibernate映射到数据库中的实体类
@Table(name="T_DEPARTMENT")声明在数据库中自动生成的表名为T_DEPARTMENT
public class Department {
@Id
@GenericGenerator(name="hibernate-native", strategy="native")
@GeneratedValue(generator="hibernate-native")
@Column(name="ID")
private Integer id;
@Column(name="DEPARTMENT_NAME")
private String departmentName;

public Department() {

}

public Department(Integer id, String departmentName) {
this.id = id;
this.departmentName = departmentName;
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getDepartmentName() {
return departmentName;
}

public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}

@Override
public String toString() {
return "Department [id=" + id + ", departmentName=" + departmentName + "]";
}

}


package com.ssh.annotation.entities;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

@Entity//声明当前类为hibernate映射到数据库中的实体类
@Table(name="T_EMPLOYEE")声明在数据库中自动生成的表名为T_DEPARTMENT
public class Employee {
@Id
@GenericGenerator(name="hibernate-native", strategy="native")
@GeneratedValue(generator="hibernate-native")
@Column(name="ID")
private Integer id;

@Column(name="LAST_NAME")
private String lastName;
@Column(name="EMAIL")
private String email;
@Column(name="BIRTH")
private Date birth;
@Column(name="CREATE_TIME")
private Date createTime;

// 单向n-1
@ManyToOne //指定多对一关系
@JoinColumn(name="DEPARTMENT_ID")
private Department department;



public Employee() {
}




public Employee(String lastName, String email, Date birth, Date createTime, Department dempartment) {
super();
this.lastName = lastName;
this.email = email;
this.birth = birth;
this.createTime = createTime;
this.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 + ", dempartment=" + department + "]";
}



}


配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">


<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/classes/log4j.properties</param-value>
</context-param>
<!-- 定义LOG4J监听器 -->
<listener>
<listener-class>
org.springframework.web.util.Log4jConfigListener
</listener-class>
</listener>

<!--1、启动Spring的容器 -->
<!-- needed for ContextLoaderListener -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>

<!-- Bootstraps the root web application context before servlet initialization -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>


配置log4j.properties

# Set root logger level to error
log4j.rootLogger=INFO, Console, File

###### Console appender definition #######

# All outputs currently set to be a ConsoleAppender.
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d{ABSOLUTE} %-5p [%c{3}] %m%n
#log4j.appender.Console.layout.ConversionPattern=%d{ABSOLUTE} %-5p [%c] %m%n

###### File appender definition #######
log4j.appender.File=org.apache.log4j.DailyRollingFileAppender
log4j.appender.File.File=spring.log
log4j.appender.File.Append=false
log4j.appender.File.layout=org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern=%d{ABSOLUTE} %-5p [%c] %m%n


启动tomcat会自动生成表结构



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" />

<!-- 扫描service自动注入为bean -->
<context:component-scan base-package="com.ssh" />

<!-- 配置数据源,使用的是alibaba的Druid数据源 -->
<bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<!-- 初始化连接大小 -->
<property name="initialSize" value="0" />
<!-- 连接池最大使用连接数量 -->
<property name="maxActive" value="20" />
<!-- 连接池最大空闲 -->
<property name="maxIdle" value="20" />
<!-- 连接池最小空闲 -->
<property name="minIdle" value="0" />
<!-- 获取连接最大等待时间 -->
<property name="maxWait" value="60000" />
<!-- <property name="poolPreparedStatements" value="true" /> <property
name="maxPoolPreparedStatementPerConnectionSize" value="33" /> -->
<property name="validationQuery" value="${validationQuery}" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<property name="testWhileIdle" value="true" />
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="25200000" />
<!-- 打开removeAbandoned功能 -->
<property name="removeAbandoned" value="true" />
<!-- 1800秒,也就是30分钟 -->
<property name="removeAbandonedTimeout" value="1800" />
<!-- 关闭abanded连接时输出错误日志 -->
<property name="logAbandoned" value="true" />
<!-- 监控数据库 -->
<!-- <property name="filters" value="stat" /> -->
<property name="filters" value="mergeStat" />
</bean>

<!-- 配置 SessionFactory -->
<!-- <bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.temp.use_jdbc_metadata_defaults">false</prop>
</props>
</property>
使用xml映射对象关系型数据库
<property name="mappingLocations" value="classpath:com/ssh/entities/*.hbm.xml"></property>
</bean> -->

<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!-- <property name="configLocation" value="classpath:hibernate.cfg.xml"></property> -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.temp.use_jdbc_metadata_defaults">false</prop>
</props>
</property>
<!-- 使用注解映射对象关系型数据库 -->
<property name="packagesToScan">
<list>
<!-- 可以加多个包 -->
<value>com.ssh.annotation.entities</value>
</list>
</property>
</bean>


<!-- 配置 Spring 的声明式事务 -->
<!-- 1. 配置 hibernate 的事务管理器 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.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.ssh.service.*.*(..))"
id="txPointcut" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" />
</aop:config>
</beans>


BaseDao


package com.ssh.dao.base;

import java.util.List;

public interface BaseDao<T> {
// 写操作
public void saveEntity(T t);

public void saveOrUpdateEntity(T t);

public void updateEntity(T t);

public void deleteEntity(T t);

public void executeByHQL(String hql, Object... objects);

// 读操作
public T loadEntity(Integer id);

public T getEntity(Integer id);

public List<T> findEntityByHQL(String hql, Object... objects);

// 单值检索,确保查询结果有且只有一条记录
public Object uniqueResult(String hql, Object... objects);
}


BaseDaoImpl


package com.ssh.dao.base;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SessionFactory;

public abstract class BaseDaoImpl<T> implements BaseDao<T> {
//注入sessionFactory
@Resource
private SessionFactory sf ;

private Class<T> clazz ;

public BaseDaoImpl(){
//得到泛型话超类
ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
clazz = (Class<T>) type.getActualTypeArguments()[0];
}

public void saveEntity(T t) {
sf.getCurrentSession().save(t);
}

public void saveOrUpdateEntity(T t) {
sf.getCurrentSession().saveOrUpdate(t);
}

public void updateEntity(T t) {
sf.getCurrentSession().update(t);
}

public void deleteEntity(T t) {
sf.getCurrentSession().delete(t);
}

/**
* 按照HQL语句进行更新,删除等操作
*/
public void executeByHQL(String hql, Object... objects) {
Query q = sf.getCurrentSession().createQuery(hql);
for(int i = 0 ; i < objects.length ; i ++){
q.setParameter(i, objects[i]);
}
q.executeUpdate();
}

public T loadEntity(Integer id) {
return (T) sf.getCurrentSession().load(clazz, id);
}

public T getEntity(Integer id) {
return (T) sf.getCurrentSession().get(clazz, id);
}

public List<T> findEntityByHQL(String hql, Object... objects) {
Query q = sf.getCurrentSession().createQuery(hql);
for(int i = 0 ; i < objects.length ; i ++){
q.setParameter(i, objects[i]);
}
return q.list();
}

//单值检索,确保查询结果有且只有一条记录
public Object uniqueResult(String hql,Object...objects){
Query q = sf.getCurrentSession().createQuery(hql);
for(int i = 0 ; i < objects.length ; i ++){
q.setParameter(i, objects[i]);
}
return q.uniqueResult();

}

}


DepartmentDao


package com.ssh.dao;

import org.springframework.stereotype.Repository;

import com.ssh.annotation.entities.Department;
import com.ssh.dao.base.BaseDaoImpl;

@Repository
public class DepartmentDao extends BaseDaoImpl<Department>{

}


EmployeeDao


package com.ssh.dao;

import org.springframework.stereotype.Repository;

import com.ssh.annotation.entities.Employee;
import com.ssh.dao.base.BaseDaoImpl;

@Repository
public class EmployeeDao extends BaseDaoImpl<Employee>{


}

DepartmentService

package com.ssh.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ssh.annotation.entities.Department;
import com.ssh.dao.DepartmentDao;

@Service
public class DepartmentService {
@Autowired
private DepartmentDao departmentDao;

public void saveDepartment(Department department){
departmentDao.saveEntity(department);
}
public void saveOrUpdate(Department department){
departmentDao.saveOrUpdateEntity(department);
}

public List<Department> getAll(){
String hql = "FROM Department";
List<Department> deptList = departmentDao.findEntityByHQL(hql);
return deptList;
}

}


EmployeeService

package com.ssh.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ssh.annotation.entities.Employee;
import com.ssh.dao.EmployeeDao;

@Service
public class EmployeeService {

@Autowired
private EmployeeDao employeeDao;



public boolean lastNameIsValid(String lastName){
String hql = "FROM Employee e WHERE e.lastName = ?";
Object uniqueResult = employeeDao.uniqueResult(hql, lastName);
return employeeDao.uniqueResult(hql, lastName)==null;
}

public void saveOrUpdate(Employee employee){
employeeDao.saveOrUpdateEntity(employee);

}

public void delete(Integer id){
String hql = "DELETE FROM Employee e WHERE e.id = ?";
employeeDao.executeByHQL(hql, id);
}

public List<Employee> getAll(){
String hql = "FROM Employee e LEFT OUTER JOIN FETCH e.department";
List<Employee> employees = employeeDao.findEntityByHQL(hql);
// employees.clear();
return employees;
}

public Employee get(Integer id) {
return employeeDao.getEntity(id);
}
}


测试

package ssh;

import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.ssh.annotation.entities.Department;
import com.ssh.service.DepartmentService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class DepartmentTest {

@Autowired
DepartmentService departmentService;

@Test
public void TestCRUD(){
Department department = new Department(null,"开发部");
departmentService.saveDepartment(department);
department = new Department(null,"产品部");
departmentService.saveDepartment(department);
department = new Department(null,"人事部");
departmentService.saveDepartment(department);
List<Department> list = departmentService.getAll();
System.out.println(list);
}

}


package ssh;

import java.util.Date;
import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.ssh.annotation.entities.Department;
import com.ssh.annotation.entities.Employee;
import com.ssh.service.DepartmentService;
import com.ssh.service.EmployeeService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class EmployeeTest {

@Autowired
DepartmentService departmentService;

@Autowired
EmployeeService employeeService;

@Test
public void TestCRUD(){
Employee employee = new Employee("AA","AA@qq.com",new Date(),new Date(),new Department(1, null));
employeeService.saveOrUpdate(employee);
employee = new Employee("bb","bb@qq.com",new Date(),new Date(),new Department(2, null));
employeeService.saveOrUpdate(employee);
employee = new Employee("小青","cc@qq.com",new Date(),new Date(),new Department(3, null));
employeeService.saveOrUpdate(employee);
}
@Test
public void getAll(){
List<Employee> all = employeeService.getAll();
System.out.println(all);
}

}


整合struct2

struct2.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="false" />

<package name="emp" namespace="/emp" extends="struts-default">

<!-- 定义新的拦截器栈, 配置 prepare 拦截器栈的 alwaysInvokePrepare 参数值为 false -->
<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/jsp/emp-list.jsp</result>
<result type="stream" name="ajax-success">
<param name="contentType">text/html</param>
<param name="inputName">inputStream</param>
</result>
<result name="input">/WEB-INF/jsp/emp-input.jsp</result>
<result name="success" type="redirect">/emp/emp-list</result>
</action>

</package>

</struts>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">


<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/classes/log4j.properties</param-value>
</context-param>
<!-- 定义LOG4J监听器 -->
<listener>
<listener-class>
org.springframework.web.util.Log4jConfigListener
</listener-class>
</listener>

<!--1、启动Spring的容器 -->
<!-- needed for ContextLoaderListener -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>

<!-- Bootstraps the root web application context before servlet initialization -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- 配置 Struts2 的 Filter -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

</web-app>

BaseAction

package com.ssh.actions;

import java.lang.reflect.ParameterizedType;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;

public abstract class BaseAction<T> extends ActionSupport implements ModelDriven<T>, Preparable {

public T model;

public BaseAction() {
try {
ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
Class clazz = (Class) type.getActualTypeArguments()[0];
model = (T) clazz.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
}

public void prepare() throws Exception {
}

public T getModel() {
return model;
}

}


EmployeeAction

package com.ssh.actions;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.struts2.interceptor.RequestAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.ssh.annotation.entities.Employee;
import com.ssh.service.DepartmentService;
import com.ssh.service.EmployeeService;

@Controller
@Scope("prototype")
public class EmployeeAction extends BaseAction<Employee> implements RequestAware{

/**
*
*/
private static final long serialVersionUID = 8915424197825150499L;

@Autowired
EmployeeService employeeService;

@Autowired
DepartmentService departmentService;

List<Employee> allEmps;



public List<Employee> getAllEmps() {
return allEmps;
}



public void setAllEmps(List<Employee> allEmps) {
this.allEmps = allEmps;

}



public String list(){
allEmps = employeeService.getAll();
// List<Employee> allEmps = employeeService.getAll();
// request.put("allEmps", allEmps);
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;
}
}


SSHDateConverter

package com.ssh.converters;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.apache.struts2.util.StrutsTypeConverter;

public class SSHDateConverter extends StrutsTypeConverter {

private DateFormat dateFormat;

{
dateFormat = new SimpleDateFormat("yyyy-MM-dd");
}

@Override
public Object convertFromString(Map context, String[] values, Class toClass) {
if(toClass == Date.class){
try {
return dateFormat.parse(values[0]);
} catch (ParseException e) {
e.printStackTrace();
}
}

return null;
}

@Override
public String convertToString(Map context, Object o) {
if(o instanceof Date){
return dateFormat.format((Date)o);
}
return null;
}

}


xwork-conversion.properties

java.util.Date=com.ssh.converters.SSHDateConverter


jsp

emp-list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="${pageContext.request.contextPath }/scripts/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(function(){
$(".delete").click(function(){
var lastName = $(this).next(":hidden").val();
var flag =confirm("你确定要删除"+lastName+"信息吗?");
if(flag){
//删除,使用ajax的方式
var $tr =$(this).parent().parent();
var url = this.href;
var args = {"time":new Date()};
$.post(url, args, function(data){
//若 data 的返回值为 1, 则提示 删除成功, 且把当前行删除
if(data == "1"){
alert("删除成功!");
$tr.remove();
}else{
//若 data 的返回值不是 1, 提示删除失败.
alert("删除失败!");
}
});
}
alert(lastName)
return false;
});
});
</script>
</head>
<body>
<h4>Employee list Page</h4>
<s:if test="allEmps == null ||allEmps.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>DEPT</td>
<td>DELETE</td>
<td>EDIT</td>
</tr>
<s:iterator value="allEmps" var="st">
<tr>
<td>${id }</td>
<td>${lastName }</td>
<td>${email }</td>
<td>
<s:date name="birth" format="yyyy-MM-dd"/>
</td>
<td>
<s:date name="birth" format="yyyy-MM-dd hh:mm:ss"/>
</td>
<td>${department.departmentName }</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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="${pageContext.request.contextPath }/scripts/jquery-1.9.1.min.js"></script>
<script type="text/javascript">

$(function(){
$(":input[name=lastName]").change(function(){
var val = $(this).val();
val = $.trim(val);
var $this = $(this);

if(val != ""){
//把当前节点后面的所有 font 兄弟节点删除
$this.nextAll("font").remove();

var url = "emp-validateLastName";
var args = {"lastName":val, "time":new Date()};
$.post(url, args, function(data){
//表示可用
if(data == "1"){
$this.after("<font color='green'>LastName可用!</font>");
}
//不可用
else if(data == "0"){
$this.after("<font color='red'>LastName不可用!</font>");
}
//服务器错误
else{
alert("服务器错误!");
}
});
}else{
alert("lastName 不能为空");
$(this).val("");
$this.focus();
}
});
})

</script>
</head>
<body>

<s:debug></s:debug>

<h4>Employee Input Page</h4>

<s:form action="emp-save" namespace="/emp" method="post">
<s:if test="id != null">
<s:textfield name="lastName" label="LastName" disabled="true"></s:textfield>
<s:hidden name="id"></s:hidden>
<%--
<!-- 通过添加隐藏域的方式把未显式提交的字段值提交到服务器 -->
<s:hidden name="lastName"></s:hidden>
<s:hidden name="createTime"></s:hidden>
--%>
</s:if>
<s:else>
<s:textfield name="lastName" label="LastName"></s:textfield>
</s:else>

<s:textfield name="email" label="Email"></s:textfield>
<s:textfield name="birth" label="Birth"></s:textfield>

<s:select list="#request.departments"
listKey="id" listValue="departmentName" name="department.id"
label="Department"></s:select>
<s:submit></s:submit>
</s:form>

</body>
</html>


index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="${pageContext.request.contextPath }/emp/emp-list">emp-list</a>

<br><br>

<a href="${pageContext.request.contextPath }/emp/emp-input">Add New Employee</a>
</body>
</html>


转:http://m.jb51.net/article/112500.htm




Caused by: java.security.AccessControlException: access denied ("java.util.PropertyPermission" "*" "read,write")

  

java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

用户名有多余的空格,复制网页上的配置可能有多余的空格,搞死人


启动tomcat超时,没显示错误

配置Log4.properties可以显示错误