jpa2.0实现: hibernate 4.1.1
连接池: BoneCP 0.7.1
缓存: ehcache 2.5.2
1、在MyEclipse下建树一个Web Project,把响应的jar到放到WEB-INFlib目次中
所需的jar:
antlr-2.7.7.jar
aopalliance-1.0.jar
aspectjrt.jar
aspectjweaver.jar
bonecp-0.7.1.RELEASE.jar
bonecp-provider-0.7.1-rc2.jar
bonecp-spring-0.7.1-rc1.jar
cglib-nodep-2.2.jar
commons-fileupload-1.2.2.jar
commons-io-2.0.1.jar
commons-lang3-3.1.jar
commons-logging-1.1.1.jar
dom4j-1.6.1.jar
ehcache-core-2.5.2.jar
freemarker-2.3.19.jar
guava-12.0.jar
hibernate-commons-annotations-4.0.1.Final.jar
hibernate-core-4.1.1.Final.jar
hibernate-entitymanager-4.1.1.Final.jar
hibernate-jpa-2.0-api-1.0.1.Final.jar
javassist-3.15.0-GA.jar
jboss-logging-3.1.0.GA.jar
jboss-transaction-api_1.1_spec-1.0.0.Final.jar
log4j-1.2.17.jar
mysql-connector-java-5.1.6-bin.jar
ognl-3.0.5.jar
org.springframework.aop-3.1.1.RELEASE.jar
org.springframework.asm-3.1.1.RELEASE.jar
org.springframework.aspects-3.1.1.RELEASE.jar
org.springframework.beans-3.1.1.RELEASE.jar
org.springframework.context-3.1.1.RELEASE.jar
org.springframework.context.support-3.1.1.RELEASE.jar
org.springframework.core-3.1.1.RELEASE.jar
org.springframework.expression-3.1.1.RELEASE.jar
org.springframework.jdbc-3.1.1.RELEASE.jar
org.springframework.jms-3.1.1.RELEASE.jar
org.springframework.orm-3.1.1.RELEASE.jar
org.springframework.oxm-3.1.1.RELEASE.jar
org.springframework.test-3.1.1.RELEASE.jar
org.springframework.transaction-3.1.1.RELEASE.jar
org.springframework.web-3.1.1.RELEASE.jar
slf4j-api-1.6.1.jar
slf4j-log4j12-1.6.1.jar
struts2-core-2.3.4.jar
struts2-spring-plugin-2.3.4.jar
xwork-core-2.3.4.jar
2、JPA2.0的设备
在src目次下建树一个名为META-INF的文件夹,在META-INF下建树一个名为persistence.xml的文件。
在persistence.xml文件中,JPA和BoneCP连接池进行了整合。
persistence.xml文件内容:
<?xml version="1.0" encoding="UTF-8"?> <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> <!-- 在应用容器经管的多半据源的景象下应用jta,不克不及应用RESOURCE-LOCAL选项 --> <persistence-unit name="APP_JPA" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <properties> <property name="javax.persistence.validation.mode" value="none"/> <!-- 若是是hibernte3,应用 <property name="hibernate.connection.provider_class" value="com.jolbox.bonecp.provider.BoneCPConnectionProvider"/> --> <!--hibernte4应用 --> <property name="hibernate.service.jdbc.connections.spi.provider_class" value="com.jolbox.bonecp.provider.BoneCPConnectionProvider"/> <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/> <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/> <property name="hibernate.connection.username" value="root"/> <property name="hibernate.connection.password" value="root"/> <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/spring_struts_jpa?useUnicode=true&characterEncoding=UTF-8"/> <property name="hibernate.max_fetch_depth" value="3"/> <property name="hibernate.hbm2ddl.auto" value=""/> <property name="hibernate.jdbc.fetch_size" value="18"/> <property name="hibernate.jdbc.batch_size" value="10"/> <property name="hibernate.show_sql" value="true"/> <property name="hibernate.format_sql" value="true"/> <!-- BoneCP参数设置 --> <!-- 设置分区个数.这个参数默认为1,建议3-4(按照特定应用法度而定) --> <property name="bonecp.partitionCount" value="3"/> <!-- 设置每个分区含有connection最大个数.这个参数默认为2.若是小于2,BoneCP将设置为50. 比如:partitionCount设置为3,maxConnectionPerPartition设置为5,你就会拥有统共15个connection.--> <property name="bonecp.maxConnectionsPerPartition" value="20"/> <!-- 设置每个分区含有连接最大小个数.这个参数默认为0 --> <property name="bonecp.minConnectionsPerPartition" value="10"/> <!-- 设置分区中的连接增长数量.这个参数默认为1 --> <property name="bonecp.acquireIncrement" value="5"/> <!-- 设置连接池阀值.这个参数默认为20.若是小于0或是大于100,BoneCP将设置为20. 连接池为每个分区至少保持20%数量的可用connection --> <property name="bonecp.poolAvailabilityThreshold" value="20"/> <!-- 设置connection助手线程个数.这个参数默认为3.若是小于0,BoneCP将设置为3. --> <property name="bonecp.releaseHelperThreads" value="3"/> <!-- 设置connection的余暇存活时候.这个参数默认为60,单位:分钟.设置为0该功能失效. 经由过程ConnectionTesterThread调查每个分区中的connection,若是这个connection间隔最 后应用的时候大于这个参数就会被清除 --> <property name="bonecp.idleMaxAge" value="240"/> <!-- 设置测试connection的间隔时候.这个参数默认为240,单位:分钟.设置为0该功能失效. 经由过程ConnectionTesterThread调查每个分区中的connection, 若是这个connection间隔最后 应用的时候大于这个参数并且间隔上一次测试的时候大于这个参数就会向数据库发送一条测试语句, 若是履行失败则将这个connection清除. --> <property name="bonecp.idleConnectionTestPeriod" value="60"/> <!-- 设置statement助手线程个数.这个参数默认为3.若是小于0,BoneCP将设置为3. --> <property name="bonecp.statementsCacheSize" value="20"/> </properties> </persistence-unit> </persistence>
3、Struts2的设备
在src目次下建树一个struts.xml文件。
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" /> <constant name="struts.objectFactory" value="spring" /> <constant name="struts.ui.theme" value="simple" /> <constant name="struts.action.extension" value="action" /> <package name="default" namespace="/" extends="struts-default"> </package> <!-- Add packages here --> </struts>
4、ehcache缓存设备
在src目次下建树名为ehcache.xml的文件。
ehcache.xml文件内容:
<?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd" Check="true" monitoring="autodetect" dynamicConfig="true"> <!-- <diskStore path="java.io.tmpdir"/> --> <!-- 设备缓存文件存放路径 --> <diskStore path="E:/cachetmpdir" /> <!-- 1.必必要有的属性: name: cache的名字,用来辨认不合的cache,必须惟一。 maxElementsInMemory: 内存经管的缓存元素数量最大限值。 maxElementsOnDisk: 硬盘经管的缓存元素数量最大限值。默认值为0,就是没有限制。 eternal: 设定元素是否持久话。若设为true,则缓存元素不会过期。 overflowToDisk: 设定是否在内存填满的时辰把数据转到磁盘上。 2.下面是一些可选属性: timeToIdleSeconds: 设定元素在过期前余暇状况的时候,只对非持久性缓存对象有效。默认值为0,值为0意味着元素可以闲置至无穷长时候。 timeToLiveSeconds: 设定元素从创建到过期的时候。其他与timeToIdleSeconds类似。 diskPersistent: 设定在虚拟机重启时是否进行磁盘存储,默认为false.(我的直觉,对于安然小型应用,宜设为true)。 diskExpiryThreadIntervalSeconds: 接见磁盘线程活动时候。 diskSpoolBufferSizeMB: 存入磁盘时的缓冲区大小,默认30MB,每个缓存都有本身的缓冲区。 memoryStoreEvictionPolicy: 元素逐出缓存规矩。共有三种,Recently Used (LRU)比来起码应用,为默认。 First In First Out (FIFO),进步前辈先出。Less Frequently Used(specified as LFU)起码应用 --> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" maxElementsOnDisk="10000000" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" /> </ehcache>
5、Spring的设置
spring经管JPA的事务、struts2的action。
在WEB-INF目次下建树一个名为applicationContext.xml的文件。
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:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:cache="http://www.springframework.org/schema/cache" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd"> <!-- 定义组件扫描,设置须要扫描的包--> <context:component-scan base-package="cn.luxh.app" /> <!-- 定义实体经管器工厂 --> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="persistenceUnitName" value="APP_JPA"/> </bean> <!-- 设置事务经管器 --> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory" /> </bean> <!-- 启用 annotation事务--> <tx:annotation-driven transaction-manager="transactionManager"/> <!-- 启用缓存注解功能 --> <cache:annotation-driven cache-manager="cacheManager"/> <!-- 声明cacheManager --> <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager" p:cacheManager-ref="ehcache" /> <!-- cacheManager工厂类,指定ehcache.xml的地位 --> <bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:configLocation="classpath:/ehcache.xml"/> </beans>
6、web.xml设置
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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <display-name>app</display-name> <!-- 设置Log4j --> <context-param> <param-name>webAppRootKey</param-name> <param-value>spring_struts_jpa.root</param-value> </context-param> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:log4j.properties</param-value> </context-param> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <!-- 设置编码过滤器 --> <filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 加载Spring器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.xml</param-value> </context-param> <!--设置缓存清除器 处理由 JavaBean Introspector功能而引起的缓存泄漏 --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <!--设置Struts2过滤器 --> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAnduteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
7、ok,Spring3+Struts2+JPA2.0整合完毕。
二、应用
1、实体类。
@Entity @Table(name="t_user") public class User implements Serializable{ private static final long serialVersionUID = -3647733101497063659L; @Id @GeneratedValue private Long id; /**账号*/ @Column(length=32) private String account; /**密码*/ @Column(length=32) private String password; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
2、DAO
1)写一个BaseDao接口和BaseDaoImpl实现类,这里是示例,只写两个办法。
@Repository用于将数据接见层 (DAO 层 ) 的类标识为 Spring Bean。
BaseDao.java:
public interface BaseDao { /** * 新增实体 * @param entity 要新增的实体 */ public void save(Object entity); /** * 按照主键查询 * @param <T> * @param clazz 实体类的Class * @param id 主键 * @return */ public <T> T getById(Class<T> clazz,Object id); }
BaseDaoImpl.java:
@Repository(value="baseDao") public class BaseDaoImpl implements BaseDao { @PersistenceContext protected EntityManager em; public void save(Object entity) { em.persist(entity); } public <T> T getById(Class<T> clazz, Object id) { return em.find(clazz, id); } }
2)写一个用户数据接见的UserDao接口和UserDaoImpl实现类。
UserDao.java:
public interface UserDao extends BaseDao{ }
UserDaoImpl.java:
@Repository(value="userDao") public class UserDaoImpl extends BaseDaoImpl implements UserDao { }
3、Service
1)BaseService接口。
public interface BaseService { /** * 新增实体 * @param entity */ public void save(Object entity); /** * 按照主键查询 * @param <T> * @param clazz 实体类的Class * @param id 主键 * @return */ public <T> T getById(Class<T> clazz,Object id); }
2)用户经管办事接口和实现类。
UserService.java:
public interface UserService extends BaseService { }
UserServiceImpl.java:
@Service(value="userService") public class UserServiceImpl implements UserService { @Resource(name="userDao") private UserDao userDao; @Override @Transactional(propagation=Propagation.REQUIRED) @CacheEvict(value="userCache",allEntries=true) public void save(Object entity) { userDao.save(entity); } @Override @Transactional(propagation=Propagation.REQUIRED,readOnly=true) @Cacheable(value="userCache") public <T> T getById(Class<T> clazz, Object id) { return userDao.getById(clazz, id); } }
@Service(value="userService") 用于将营业层的类标识为 Spring Bean。
@Resource(name="userDao") 按照名字注入资料
@Transactional(propagation=Propagation.REQUIRED) 注解式事务
@Cacheable(value="userCache") 注解式缓存,将办法的返回值参加到名称为userCache的缓存中
@CacheEvict(value="userCache",allEntries=true) 注解式缓存,清除缓存名称为userCache缓存
4、缓存文件设备
在ehcache.xml中设备userCache缓存。
<?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd" Check="true" monitoring="autodetect" dynamicConfig="true"> <!-- <diskStore path="java.io.tmpdir"/> --> <!-- 设备缓存文件存放路径 --> <diskStore path="E:/cachetmpdir" /> <!-- 1.必必要有的属性: name: cache的名字,用来辨认不合的cache,必须惟一。 maxElementsInMemory: 内存经管的缓存元素数量最大限值。 maxElementsOnDisk: 硬盘经管的缓存元素数量最大限值。默认值为0,就是没有限制。 eternal: 设定元素是否持久话。若设为true,则缓存元素不会过期。 overflowToDisk: 设定是否在内存填满的时辰把数据转到磁盘上。 2.下面是一些可选属性: timeToIdleSeconds: 设定元素在过期前余暇状况的时候,只对非持久性缓存对象有效。默认值为0,值为0意味着元素可以闲置至无穷长时候。 timeToLiveSeconds: 设定元素从创建到过期的时候。其他与timeToIdleSeconds类似。 diskPersistent: 设定在虚拟机重启时是否进行磁盘存储,默认为false.(我的直觉,对于安然小型应用,宜设为true)。 diskExpiryThreadIntervalSeconds: 接见磁盘线程活动时候。 diskSpoolBufferSizeMB: 存入磁盘时的缓冲区大小,默认30MB,每个缓存都有本身的缓冲区。 memoryStoreEvictionPolicy: 元素逐出缓存规矩。共有三种,Recently Used (LRU)比来起码应用,为默认。 First In First Out (FIFO),进步前辈先出。Less Frequently Used(specified as LFU)起码应用 --> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" maxElementsOnDisk="10000000" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" /> <!-- User cache --> <cache name="userCache" maxElementsInMemory="10000" maxElementsOnDisk="1000" eternal="false" overflowToDisk="true" diskSpoolBufferSizeMB="20" timeToIdleSeconds="300" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LFU" /> </ehcache>
5、Action
UserAction.java:
@Controller @Scope("prototype") public class UserAction extends ActionSupport{ @Resource(name="userService") private UserService userService; /** * 保存用户 */ public String saveUser() { User user = new User(); user.setAccount("admin"); user.setPassword("admin"); userService.saveEntity(user); return SUCCESS; } /** * 按照ID查找用户 */ public String findUserById() { long id = 1L; User user = userService.getById(User.class, id); return SUCCESS; } }
@Controller(value="userService") 用于将把握层的类标识为 Spring Bean。
6、在struts.xml添加action的设备
<?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" /> <constant name="struts.objectFactory" value="spring" /> <constant name="struts.ui.theme" value="simple" /> <constant name="struts.action.extension" value="action" /> <package name="default" namespace="/" extends="struts-default"> <!-- 保存用户 --> <action name="saveUser" class="userAction" method="saveUser"> <result>/WEB-INF/page/user/userList.jsp</result> </action> <!-- 按照ID查找用户 --> <action name="findUserById" class="userAction" method="findUserById"> <result>/WEB-INF/page/user/userDetail.jsp</result> </action> </package> <!-- Add packages here --> </struts>