在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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.temp</groupId> <artifactId>ssh</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>ssh Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <hibernate.version>5.2.12.Final</hibernate.version> <mysql.version>5.1.44</mysql.version> <spring.version>5.0.1.RELEASE</spring.version> <struts2.version>2.5.13</struts2.version> <slf4j.version>1.7.7</slf4j.version> <log4j2.version>2.9.1</log4j2.version> <disruptor.version>3.2.0</disruptor.version> <junit.version>4.12</junit.version> <javax.servlet.version>4.0.0</javax.servlet.version> <jstl.version>1.2</jstl.version> <standard.version>1.1.2</standard.version> <tomcat-jsp-api.version>8.0.47</tomcat-jsp-api.version> </properties> <dependencies> <!-- 1、导入hibernate依赖 --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-c3p0</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-ehcache</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>${struts2.version}</version> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-spring-plugin</artifactId> <version>${struts2.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>${slf4j.version}</version> <scope>runtime</scope> </dependency> <!--需要使用log4j2的AsyncLogger需要包含disruptor --> <dependency> <groupId>com.lmax</groupId> <artifactId>disruptor</artifactId> <version>${disruptor.version}</version> </dependency> <!-- 5.1、junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <!-- 5.2、servlet --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${javax.servlet.version}</version> <scope>provided</scope> </dependency> <!-- 5.3、jstl、standard --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>${jstl.version}</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>${standard.version}</version> </dependency> <!-- 5.4、tomcat-jsp-api --> <dependency> <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-jsp-api</artifactId> <version>${tomcat-jsp-api.version}</version> </dependency> </dependencies> <build> <finalName>ssh</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> </configuration> </plugin> </plugins> </build> </project>
导入以下文件
ehcache.xml
<?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" updateCheck="false"> <!--磁盘存储:将缓存中暂时不使用的对象,转移到硬盘,类似于Windows系统的虚拟内存--> <!--path:指定在硬盘上存储对象的路径--> <!--java.io.tmpdir 是默认的临时文件路径。 可以通过如下方式打印出具体的文件路径 System.out.println(System.getProperty("java.io.tmpdir"));--> <diskStore path="java.io.tmpdir"/> <!--defaultCache:默认的管理策略--> <!--eternal:设定缓存的elements是否永远不过期。如果为true,则缓存的数据始终有效,如果为false那么还要根据timeToIdleSeconds,timeToLiveSeconds判断--> <!--maxElementsInMemory:在内存中缓存的element的最大数目--> <!--overflowToDisk:如果内存中数据超过内存限制,是否要缓存到磁盘上--> <!--diskPersistent:是否在磁盘上持久化。指重启jvm后,数据是否有效。默认为false--> <!--timeToIdleSeconds:对象空闲时间(单位:秒),指对象在多长时间没有被访问就会失效。只对eternal为false的有效。默认值0,表示一直可以访问--> <!--timeToLiveSeconds:对象存活时间(单位:秒),指对象从创建到失效所需要的时间。只对eternal为false的有效。默认值0,表示一直可以访问--> <!--memoryStoreEvictionPolicy:缓存的3 种清空策略--> <!--FIFO:first in first out (先进先出)--> <!--LFU:Less Frequently Used (最少使用).意思是一直以来最少被使用的。缓存的元素有一个hit 属性,hit 值最小的将会被清出缓存--> <!--LRU:Least Recently Used(最近最少使用). (ehcache 默认值).缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存--> <defaultCache eternal="false" maxElementsInMemory="1000" overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU"/> <!--name: Cache的名称,必须是唯一的(ehcache会把这个cache放到HashMap里)--> <cache name="stuCache" eternal="false" maxElementsInMemory="100" overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0" timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU"/> </ehcache>
hibernate-context2.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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!-- 1、注册jdbc相关的配置文件 --> <context:property-placeholder location="classpath:db.properties" /> <!-- 2、配置数据库连接池C3P0 --> <!-- 注册数据库连接文件db.properties --> <!-- 配置c3p0连接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="${db.username}"></property> <property name="password" value="${db.password}"></property> <property name="driverClass" value="${db.driverClass}"></property> <property name="jdbcUrl" value="${db.jdbcUrl}"></property> <!--初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 --> <property name="initialPoolSize" value="${db.initialPoolSize}"></property> <!--连接池中保留的最大连接数。Default: 15 --> <property name="maxPoolSize" value="${db.maxPoolSize}"></property> <!--连接池中保留的最小连接数。 --> <property name="minPoolSize" value="${db.minPoolSize}" /> <!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 --> <property name="maxIdleTime" value="${db.maxIdleTime}" /> <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 --> <property name="acquireIncrement" value="${db.acquireIncrement}" /> <!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements 属于单个connection而不是整个连接池。 所以设置这个参数需要考虑到多方面的因素。如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0 --> <property name="maxStatements" value="${db.maxStatements}" /> <!--每60秒检查所有连接池中的空闲连接。Default: 0 --> <property name="idleConnectionTestPeriod" value="${db.idleConnectionTestPeriod}" /> <!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 --> <property name="acquireRetryAttempts" value="${db.acquireRetryAttempts}" /> <!--获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效 保留,并在下次调用getConnection()的时候继续尝试获取连接。 如果设为true,那么在尝试 获取连接失败后该数据源将申明已断开并永久关闭。Default: false --> <property name="breakAfterAcquireFailure" value="${db.breakAfterAcquireFailure}" /> <!--因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection提交的 时候都将校验其有效性。建议使用idleConnectionTestPeriod 或automaticTestTable 等方法来提升连接测试的性能。Default: false --> <property name="testConnectionOnCheckout" value="${db.breakAfterAcquireFailure}" /> </bean> <!-- 3、配置sessionfactory相关信息 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <!-- 数据源 --> <property name="dataSource"> <ref bean="dataSource" /> </property> <!-- hibernate相关属性 --> <property name="hibernateProperties"> <props> <prop key="dialect">org.hibernate.dialect.MySQLDialect</prop> <!--spring与Hibernate集成无法显示sql语句问题,请见集成后hibernate无法显示sql语句.txt --> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> </props> </property> <!-- 实体映射文件 --> <property name="mappingResources"> <list> <value>com/javaxl/book/entity/Book.hbm.xml</value> </list> </property> </bean> <!-- 4、配置事务 --> <!--声明式事务配置开始 --> <!-- 静态代理: 一个代理对象->一个目标对象 BookProxy(BookBizImpl+myMethodBeforeAdvice)->bookBiz OrderProxy(OrderBizImpl+myMethodBeforeAdvice2)-> OrderBiz 动态代理: 一个代理对象->多个目标对象 --> <!--1) 开启自动代理 --> <aop:aspectj-autoproxy /> <!--2) 事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!--3) 定义事务特性 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="edit*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="del*" propagation="REQUIRED" /> <tx:method name="remove*" propagation="REQUIRED" /> <tx:method name="load*" propagation="REQUIRED" read-only="true" /> <tx:method name="list*" propagation="REQUIRED" read-only="true" /> <tx:method name="select*" propagation="REQUIRED" read-only="true" /> <tx:method name="query*" propagation="REQUIRED" read-only="true" /> <tx:method name="do*" propagation="REQUIRED" /> </tx:attributes> </tx:advice> <!--4) 定义切入点 --> <aop:config> <!-- pointcut属性用来定义一个切入点,分成四个部分理解 [* ][*..][*Biz][.*(..)] --> <!-- A: 返回类型,*表示返回类型不限 --> <!-- B: 包名,*..表示包名不限 --> <!-- C: 类或接口名,*Biz表示类或接口必须以Biz结尾 --> <!-- D: 方法名和参数,*(..)表示方法名不限,参数类型和个数不限 --> <aop:advisor advice-ref="txAdvice" pointcut="execution(* *..*Biz.*(..))" /> </aop:config> <!-- 声明式事务配置结束 --> <!-- 5、配置HibernateTemplate --> <bean class="org.springframework.orm.hibernate5.HibernateTemplate" id="hibernateTemplate"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 6、分模块开发(只配置base模块) --> <bean class="com.base.entity.BaseEntity" abstract="true" id="baseEntity"></bean> <bean class="com.base.dao.Basedao" abstract="true" id="baseDao" > <property name="hibernateTemplate" ref="hibernateTemplate"></property> </bean> <bean class="com.base.biz.BaseBiz" abstract="true" id="baseBiz"></bean> <bean class="com.base.web.BaseAction" abstract="true" id="baseAction"></bean> <!-- --> </beans>
spring-book.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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <bean class="com.book.dao.BookDao" parent="baseDao" id="BookDao"></bean> <bean class="com.book.biz.BookbizImpl" parent="baseBiz" id="Bookbiz"> <property name="BookDao" ref="BookDao"></property> </bean> <bean class="com.book.web.BookAction" parent="baseAction" id="BookAction"> <property name="BookBiz" ref="BookBiz"></property> </bean> </beans>
struts-book.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd"> <struts> <package name="book" extends="base" namespace="/book"> <action name="/Book_*" class="BookAction" method="{1}"> </action> </package> </struts>
后面再是方法:
需要导入两个用到的类
basedao:
package com.base.dao; import java.awt.print.Pageable; import java.io.Serializable; import java.util.Collection; import java.util.List; import java.util.Map; import org.hibernate.Session; import org.hibernate.query.Query; import org.springframework.orm.hibernate5.support.HibernateDaoSupport; import com.base.util.PageBean; public class Basedao extends HibernateDaoSupport implements Serializable{ public void setParam(Query query,Map<String, Object> map) { if(map == null || map.size() < 1) { return; } Object value = null; for(Map.Entry<String, Object> entry:map.entrySet()) { value = entry.getValue(); if(value instanceof Collection) { query.setParameterList(entry.getKey(), (Collection) value); }else if(value instanceof Object[]) { query.setParameterList(entry.getKey(), (Object[]) value); }else { query.setParameter(entry.getKey(), value); } } } public String getCountHql(String hql) { int index = hql.toUpperCase().indexOf("FROM"); return "select count(*) "+hql.substring(index); } /** * * @param hql 已经拼装好的 * @param map * @param pageBean * @return */ public List executeQuery(Session session, String hql,Map<String, Object> map,PageBean pageBean) { if(pageBean !=null && pageBean.isPagination()) { String countHql = getCountHql(hql); Query countQuery = session.createQuery(countHql); this.setParam(countQuery, map); pageBean.setTotal(countQuery.getSingleResult().toString()); Query query = session.createQuery(hql); this.setParam(query, map); query.setFirstResult(pageBean.getStartIndex()); query.setMaxResults(pageBean.getRows()); List list = query.list(); return list; }else { Query query = session.createQuery(hql); this.setParam(query, map); List list = query.list(); return list; } } }
baseentity:
package com.base.entity; import java.io.Serializable; /** * \ * 这里存放所有实体类的共性属性 * jsp传递到后台的参数 * 非数据库与表的映射关系的字段属性 * @author 11 * */ public class BaseEntity implements Serializable{ }
bookaction:
package com.base.web; import java.io.Serializable; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts2.interceptor.ServletRequestAware; import org.apache.struts2.interceptor.ServletResponseAware; public class BaseAction implements ServletRequestAware, ServletResponseAware,Serializable{ private static final long serialVersionUID = -7110462505161900879L; /** * 为了传值使用 */ protected HttpServletResponse response; protected HttpServletRequest request; protected HttpSession session; protected ServletContext application; /** * 为了配置跳转页面所用 */ protected final static String SUCCESS = "success"; protected final static String FAIL = "fail"; protected final static String LIST = "list"; protected final static String ADD = "add"; protected final static String EDIT = "edit"; protected final static String DETAIL = "detail"; /** * 具体传值字段 后端向jsp页面传值所用字段 */ protected Object result; protected Object msg; protected int code; public Object getResult() { return result; } public Object getMsg() { return msg; } public int getCode() { return code; } @Override public void setServletResponse(HttpServletResponse arg0) { this.response = arg0; } @Override public void setServletRequest(HttpServletRequest arg0) { this.request = arg0; this.session = arg0.getSession(); this.application = arg0.getServletContext(); } }
book包:
bookbiz接口:
package com.book.biz; import java.util.List; import org.hibernate.HibernateException; import org.hibernate.Session; import org.springframework.orm.hibernate5.HibernateCallback; import com.book.entity.Book; public interface BookBiz { public int add(Book book); public void edit(Book book); public void del(Book book); public List<Book> list(); }
实现类:
package com.book.biz; import java.util.List; import org.hibernate.HibernateException; import org.hibernate.Session; import org.springframework.orm.hibernate5.HibernateCallback; import com.book.entity.Book; public interface BookBiz { public int add(Book book); public void edit(Book book); public void del(Book book); public List<Book> list(); }
bookdao:
package com.book.dao; import java.util.List; import org.hibernate.HibernateException; import org.hibernate.Session; import org.springframework.orm.hibernate5.HibernateCallback; import com.base.dao.Basedao; import com.book.entity.Book; /** * 一定要继承Basedao(是为了获取到hibernateTemplete) * 方法命名有讲究(一定要符合声明式事务所定义的规则) * hibernateTemplete模板在执行查询的时候比较特殊 * * @author 11 * */ public class BookDao extends Basedao{ public int add(Book book) { return (int) getHibernateTemplate().save(book); } public void edit(Book book) { getHibernateTemplate().update(book); } public void del(Book book) { getHibernateTemplate().delete(book); } public List<Book> list(){ return (List<Book>) getHibernateTemplate().execute(new HibernateCallback<List<Book>>() { @Override public List<Book> doInHibernate(Session session) throws HibernateException { // TODO Auto-generated method stub return session.createQuery("from Book").list(); } }); } }
然后再是实体类与映射文件的导入
最后再是bookaction
package com.book.web; import java.util.List; import com.base.web.BaseAction; import com.book.biz.BookBiz; import com.book.entity.Book; import com.opensymphony.xwork2.ModelDriven; public class BookAction extends BaseAction implements ModelDriven<Book> { private Book book=new Book(); private BookBiz bookbiz; public BookBiz getBookbiz() { return bookbiz; } public void setBookbiz(BookBiz bookbiz) { this.bookbiz = bookbiz; } @Override public Book getModel() { // TODO Auto-generated method stub return book; } public String add() { System.out.println(book); this.bookbiz.add(book); return null; } public String edit() { System.out.println(book); this.bookbiz.edit(book); return null; } public String del() { System.out.println(book); this.bookbiz.del(book); return null; } public String list() { List<Book> list2=this.bookbiz.list(); for (Book book : list2) { System.out.println(book); } return null; } }