1、建立web应用
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <!-- Add Support for Spring --> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <!-- jsf额外需要的spring监视器 --> <listener> <listener-class> org.springframework.web.context.request.RequestContextListener </listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring-config.xml</param-value> </context-param> <!-- log4配置 --> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>/WEB-INF/classes/log4j.properties</param-value> </context-param> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <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> <!-- 字符编码过滤器 --> <filter> <filter-name>encodingFilter</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>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.xhtml</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.jsf</url-pattern> </servlet-mapping> <!-- JSF2.0的模式配置,开发模式下会在调试时报更加详细的错误--> <context-param> <param-name>javax.faces.PROJECT_STAGE</param-name> <param-value>Development</param-value> </context-param> <welcome-file-list> <welcome-file>index.jsf</welcome-file> </welcome-file-list> </web-app>
2、配置 sping配置
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:aop="http://www.springframework.org/schema/aop" 6 xmlns:tx="http://www.springframework.org/schema/tx" 7 xmlns:jpa="http://www.springframework.org/schema/data/jpa" 8 xsi:schemaLocation="http://www.springframework.org/schema/beans 9 http://www.springframework.org/schema/beans/spring-beans.xsd 10 http://www.springframework.org/schema/tx 11 http://www.springframework.org/schema/tx/spring-tx-3.1.xsd 12 http://www.springframework.org/schema/context 13 http://www.springframework.org/schema/context/spring-context-3.1.xsd 14 http://www.springframework.org/schema/aop 15 http://www.springframework.org/schema/aop/spring-aop-3.1.xsd 16 17 http://www.springframework.org/schema/data/jpa 18 http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd 19 20 21 "> 22 23 <bean 24 class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 25 <property name="location"> 26 <value>classpath:config/database/db.properties</value> 27 </property> 28 </bean> 29 30 <bean id="DataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 31 <property name="driverClassName" value="${jdbc.driverClassName}"/> 32 <property name="url" value="${jdbc.url}"/> 33 <property name="username" value="${jdbc.username}"/> 34 <property name="password" value="${jdbc.password}"/> 35 </bean> 36 <!--bean id="SessionFactory" 37 class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> 38 39 <property name="dataSource"> 40 <ref bean="DataSource"/> 41 </property> 42 43 <property name="hibernateProperties"> 44 <props> 45 <prop key="hibernate.dialect">${hibernate.dialect}</prop> 46 <prop key="hibernate.show_sql">true</prop> 47 <prop key="hibernate.connection.url">jdbc:hsqldb:file:E:DB/metaDB.db</prop> 48 <prop key="hibernate.connection.driver_class">org.hsqldb.jdbc.JDBCDriver</prop> 49 <prop key="hibernate.connection.username">sa</prop> 50 <prop key="hibernate.connection.password"></prop> 51 </props> 52 </property> 53 <property name="mappingDirectoryLocations"> 54 <list> 55 <value>classpath:com/hantongchao/entity</value> 56 </list> 57 </property> 58 <property name="packagesToScan"> 59 <array> 60 <value>com.hantongchao.entity</value> 61 </array> 62 </property> 63 64 65 </bean--> 66 <bean id="timeWeaver" class="com.hantongchao.common.ExtInstrumentationLoadTimeWeaver"/> 67 <context:annotation-config /> 68 <context:component-scan base-package="com.hantongchao.service,com.hantongchao.version,com.hantongchao.common" resource-pattern="**/*.class" 69 name-generator="org.springframework.context.annotation.AnnotationBeanNameGenerator" 70 use-default-filters="true" 71 annotation-config="true" > 72 <!-- entity 类自动注册 73 <context:include-filter type="annotation" expression="javax.persistence.Entity"/> 74 <context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/> 75 --> 76 </context:component-scan> 77 <context:load-time-weaver aspectj-weaving="autodetect" weaver-class="com.hantongchao.common.ExtInstrumentationLoadTimeWeaver" /> 78 <!-- Enable the configuration of transactional behavior based on annotations --> 79 <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/> 80 81 <!-- Transaction Manager is defined --> 82 <!--bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> 83 <property name="sessionFactory" ref="SessionFactory"/> 84 </bean--> 85 <bean id="provider" class="org.hibernate.ejb.HibernatePersistence"/> 86 <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> 87 <!--property name="dataSource" ref="DataSource" /--> 88 <property name="persistenceProvider" ref="provider"/> 89 <!--property name="persistenceUnitName" value="metadata_app_jpa" /--> 90 <!--property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml" /--> 91 <property name="loadTimeWeaver" ref="timeWeaver"/> 92 <!--property name="packagesToScan" value="com.hantongchao.entity" /--> 93 <property name="jpaDialect" ref="jpaDialect"/> 94 <property name="jpaVendorAdapter" ref="HibernateJpaVendorAdapter"> 95 96 </property> 97 </bean> 98 <bean id="HibernateJpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> 99 <property name="databasePlatform" value="${hibernate.dialect}" /> 100 <property name="generateDdl" value="false" /> 101 </bean> 102 <bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/> 103 <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" lazy-init="true"> 104 <property name="entityManagerFactory" ref="entityManagerFactory"/> 105 </bean> 106 107 <tx:advice id="transactionAdvice" transaction-manager="transactionManager"> 108 <tx:attributes> 109 <tx:method name="*" rollback-for="Exception" /> 110 <tx:method name="insert*" propagation="REQUIRED" /> 111 <tx:method name="del*" propagation="REQUIRED" /> 112 <tx:method name="update*" propagation="REQUIRED" /> 113 114 <tx:method name="save*" propagation="REQUIRED" /> 115 <tx:method name="create*" propagation="REQUIRED" /> 116 <tx:method name="*" read-only="true" /> 117 </tx:attributes> 118 </tx:advice> 119 <aop:aspectj-autoproxy/> 120 <aop:config> 121 <aop:aspect ref="versionAspect"> 122 <aop:pointcut id="versionCut" expression="execution(* com.hantongchao.service.*.*(..))" /> 123 <aop:before pointcut-ref="versionCut" method="before" /> 124 <aop:around pointcut-ref="versionCut" method="around" /> 125 </aop:aspect> 126 </aop:config> 127 <aop:config> 128 <aop:pointcut id="businessService" expression="execution(* com.hantongchao.service.*.*(..))" /> 129 <aop:advisor advice-ref="transactionAdvice" pointcut-ref="businessService" /> 130 </aop:config> 131 132 133 134 <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/> 135 <!-- 需要在 <beans> 标签中增加对 jpa 命名空间的引用 --> 136 <jpa:repositories base-package="com.hantongchao.repository" transaction-manager-ref="transactionManager" 137 entity-manager-factory-ref="entityManagerFactory"/> 138 139 <bean id="entityPatten" class="java.lang.String"> 140 <constructor-arg value="com.hantongchao.entity.*"/> 141 </bean> 142 <bean id="entityMethodList" class="java.util.ArrayList"> 143 144 </bean> 145 <!--bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 146 <property name="viewClass"> 147 <value> 148 org.springframework.web.servlet.view.JstlView 149 </value> 150 </property> 151 <property name="prefix"> 152 <value>/WEB-INF/jsp/</value> 153 </property> 154 <property name="suffix"> 155 <value>.jsp</value> 156 </property> 157 </bean--> 158 </beans>
3、建立 service
package com.hantongchao.service; import com.hantongchao.entity.UserEntity; import java.util.List; /** * Created by han on 14-3-7. */ public interface IUserService { public List<UserEntity> getAll(); public UserEntity save(UserEntity userEntity); public void deleteAll(); }
package com.hantongchao.service.imp; import com.hantongchao.entity.AccountEntity; import com.hantongchao.entity.UserEntity; import com.hantongchao.mbean.UserEntityManagedBean; import com.hantongchao.repository.IAccountDao; import com.hantongchao.repository.IUserDao; import com.hantongchao.service.IUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * Created with IntelliJ IDEA. * User: han * Date: 14-3-5 * Time: 上午9:41 * To change this template use File | Settings | File Templates. */ @Service public class UserService implements IUserService { @Autowired private IUserDao userDao; @Autowired private IAccountDao accountDao; @Override public List<UserEntity> getAll(){ List<UserEntity> list = userDao.findAll(); return list; } @Override public UserEntity save(UserEntity userEntity){ userDao.save(userEntity); return userEntity; } public void deleteAll(){ userDao.deleteAll(); } }
4、DAO
package com.hantongchao.repository; import com.hantongchao.entity.UserEntity; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Component; import org.springframework.stereotype.Repository; /** * Created by han on 14-3-7. */ @Repository("userDao") public interface IUserDao extends MyJpaRepository <UserEntity, Integer> { }
4、entity
package com.hantongchao.entity; import javax.persistence.*; import java.math.BigInteger; import java.sql.Timestamp; import java.util.HashSet; import java.util.Set; /** * Created by han on 14-3-6. */ @Entity @Table(name = "USER", schema = "PUBLIC", catalog = "PUBLIC") public class UserEntity implements VersionEntity { private BigInteger user_id; private String name; private String surname; private Set<AccountEntity> accountEntities = new HashSet<AccountEntity>(); private Timestamp startdate; private Timestamp enddate; private BigInteger versionid; @Basic @Column(name = "USER_ID",nullable = true) public BigInteger getUser_id() { return user_id; } public void setUser_id(BigInteger user_id) { this.user_id = user_id; } @Basic @Column(name = "NAME", nullable = false, insertable = true, updatable = true, length = 45, precision = 0) public String getName() { return name; } public void setName(String name) { this.name = name; } @Basic @Column(name = "SURNAME", nullable = false, insertable = true, updatable = true, length = 45, precision = 0) public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } @OneToMany( cascade = (CascadeType.ALL),fetch=FetchType.EAGER ,mappedBy = "user") public Set<AccountEntity> getAccountEntities() { return accountEntities; } public void setAccountEntities(Set<AccountEntity> accountEntities) { this.accountEntities = accountEntities; } public UserEntity addAccount(AccountEntity accountEntity){ accountEntity.setUser(this); this.getAccountEntities().add(accountEntity); return this; } @Basic @Column(name = "STARTDATE") public Timestamp getStartdate() { return startdate; } public void setStartdate(Timestamp startdate) { this.startdate = startdate; } @Basic @Column(name = "ENDDATE") public Timestamp getEnddate() { return enddate; } public void setEnddate(Timestamp enddate) { this.enddate = enddate; } @Id @Column(name = "VERSIONID") @GeneratedValue(strategy = GenerationType.TABLE,generator="userIdGen") @TableGenerator(name="userIdGen",allocationSize = 1) public BigInteger getVersionid() { return versionid; } public void setVersionid(BigInteger versionid) { this.versionid = versionid; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; UserEntity that = (UserEntity) o; if (user_id != that.user_id) return false; if (enddate != null ? !enddate.equals(that.enddate) : that.enddate != null) return false; if (name != null ? !name.equals(that.name) : that.name != null) return false; if (startdate != null ? !startdate.equals(that.startdate) : that.startdate != null) return false; if (surname != null ? !surname.equals(that.surname) : that.surname != null) return false; if (versionid != null ? !versionid.equals(that.versionid) : that.versionid != null) return false; return true; } @Override public int hashCode() { int result = (user_id!=null?user_id.intValue():0); result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + (surname != null ? surname.hashCode() : 0); result = 31 * result + (startdate != null ? startdate.hashCode() : 0); result = 31 * result + (enddate != null ? enddate.hashCode() : 0); result = 31 * result + (versionid != null ? versionid.hashCode() : 0); return result; } @Override public BigInteger Key() { return this.getUser_id(); } }
5、JPA
<?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"> <persistence-unit name="metadata_app_jpa" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <properties> <property name="hibernate.max_fetch_depth" value="3"/> <property name="hibernate.jdbc.fetch_size" value="50"/> <property name="hibernate.jdbc.batch_size" value="50"/> <property name="hibernate.show_sql" value="true"/> <property name="hibernate.format_sql" value="false"/> <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/> <property name="hibernate.connection.url" value="jdbc:hsqldb:file:E:DB/metaDB.db"/> <property name="hibernate.connection.driver_class" value="org.hsqldb.jdbc.JDBCDriver"/> <property name="hibernate.connection.username" value="sa"/> <property name="hibernate.connection.password" value=""/> <property name="hibernate.ejb.entitymanager_factory_name" value="entityManagerFactory"/> </properties> </persistence-unit> </persistence>
读取配置文件
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>classpath:config/database/db.properties</value>
</property>
</bean>
<context:annotation-config />
<context:component-scan base-package="com.hantongchao.service,com.hantongchao.version,com.hantongchao.common" resource-pattern="**/*.class"
name-generator="org.springframework.context.annotation.AnnotationBeanNameGenerator"
use-default-filters="true"
annotation-config="true" >
</context:component-scan>
注解和扫描bean
<aop:aspectj-autoproxy/>
<aop:config>
<aop:aspect ref="versionAspect">
<aop:pointcut id="versionCut" expression="execution(* com.hantongchao.service.*.*(..))" />
<aop:before pointcut-ref="versionCut" method="before" />
<aop:around pointcut-ref="versionCut" method="around" />
</aop:aspect>
</aop:config>
<aop:config>
<aop:pointcut id="businessService" expression="execution(* com.hantongchao.service.*.*(..))" />
<aop:advisor advice-ref="transactionAdvice" pointcut-ref="businessService" />
</aop:config>
两个AOP一个是事务处理,一个准备做版本管理
public Object around(ProceedingJoinPoint jp) throws Throwable { System.out.println("Spring AOP: Around advice"); Signature signature= jp.getSignature(); String declaringTypeName= signature.getDeclaringTypeName(); String name= signature.getName(); Object [] args=jp.getArgs(); if(args.length>0){ System.out.print("Arguments passed: "); for (int i = 0; i < args.length; i++) { System.out.print("Arg"+(i+1)+":"+args[i]); String className=args[i].getClass().getCanonicalName(); if( this.P.matcher(className).matches()){ Object classz=args[i]; if (name=="save") { // VersionEntity entity=(VersionEntity)args[i]; // VersionEntity old= entity.getOldEntity(); // if( !CompareUtil.compare(entity,old)) /* { if(entity.getEnddate()==null) entity.setEnddate(new Timestamp(9999,12,31,12,59,59,59)); //insert entity.setEnddate(new Timestamp(Calendar.getInstance().getTimeInMillis())); jp.proceed(args); entity.setVersionid(BigInteger.valueOf(entity.getVersionid().longValue() +1)); entity.setStartdate(entity.getEnddate()); entity.setEnddate(new Timestamp(9999,12,31,12,59,59,59)); //insert return jp.proceed(args); } */ } }; } }
还没有想好如何完成数据表的版本管理,只是测试了weaver是可行了能够获得参数信息,如果判断是保存。。