使用了很长时间的Spring2.5+Struts2.1.X+Hibernate3.3,也作了不少的项目,之前的 Struts2+Spring2.5+Hibernate3(JPA)+ExtJS3基本后台-2010-3-4修改 就是基于SSH2做的。不过偶还算是比较喜欢尝新的,看到Spring3的发布还有JPA2.0的标准草案还是非常滴兴奋,经过两天的学习基本构建并发布成功。这里不对这两个架构的优劣进行比较,毕竟还在学习阶段,等有了一些心得在来和大家分享吧。
注:下载包内没有库文件和数据库文件,库请自行按下面列表添加,sql文件请下载 Struts2+Spring2.5+Hibernate3(JPA)+ExtJS3基本后台-2010-3-4修改 里面的sql包
commons-beanutils.jar
commons-collections-3.2.1.jar
commons-lang-2.1.jar
commons-logging.jar
commons-pool-1.5.3.jar
com.springsource.org.aopalliance-1.0.0.jar
derby-10.5.3.0_1.jar
freemarker.jar
geronimo-jms_1.1_spec-1.1.1.jar
geronimo-jpa_2.0_spec-1.0.jar
geronimo-jta_1.1_spec-1.1.1.jar
hibernate-validator-4.0.2.GA.jar
log4j-1.2.15.jar
mysql-connector-java-5.1.7-bin.jar
openjpa-2.0.0-beta2.jar
org.springframework.aop-3.0.1.RELEASE-A.jar
org.springframework.asm-3.0.1.RELEASE-A.jar
org.springframework.beans-3.0.1.RELEASE-A.jar
org.springframework.context-3.0.1.RELEASE-A.jar
org.springframework.context.support-3.0.1.RELEASE-A.jar
org.springframework.core-3.0.1.RELEASE-A.jar
org.springframework.expression-3.0.1.RELEASE-A.jar
org.springframework.instrument-3.0.1.RELEASE-A.jar
org.springframework.jdbc-3.0.1.RELEASE-A.jar
org.springframework.orm-3.0.1.RELEASE-A.jar
org.springframework.transaction-3.0.1.RELEASE-A.jar
org.springframework.web-3.0.1.RELEASE-A.jar
org.springframework.web.servlet-3.0.1.RELEASE-A.jar
serp-1.13.1.jar
slf4j-api-1.5.10.jar
slf4j-log4j12-1.5.10.jar
validation-api-1.0.0.GA.jar
=======================废话的分割线=======================
下载 Spring 3.01 OpenJPA 2.0 Beta(看他们的路线图4月初就要出待选正式版了) Tomcat 6
这里是用的开发平台是Eclipse3.5 JavaEE,其中的WTP带了JPA的管理工具
=======================准备完成的分割线=======================
新建一个WEB项目
这里要修改一下,点Modify
选中Java Persistence这样的话建好的项目才能使用JPA的管理工具
好了,下一步,这里我不建议选择JPA implementation 和 Add driver library to build path,因为在最后的发布中很奇怪的是有时候不能把自己定义的JPA、Spring、JDBC的库发布到WEB的目录里面,修改了项目的classes文件也不行。另外 Create orm.xml 也不要选了,反正我不准备使用orm.xml来配置POJO。
配置数据库链接的方法在下面的下面
配置数据库链接,JDBC驱动的配置就不说了吧
完成,一个WEB的项目就建好了。在Eclipse里面右键点这个项目,选择JPA Tools -> Generate Entities from Tables。下面那个勾勾要选上,这样就会把POJO的对象列到JPA的配置文件里面(其实不列进去也可以要到其他地方配置,这里就不说了)。
这里是配置映射管理的界面,比以前好多了……感动啊,考虑到效率问题一般我不配置一对多的关系,又在用户表中有三个字段与部门表关联,所以关联的名字改了一下
我习惯使用List,大家看自己来选这个吧。所在包位置我选的是jpa。因为使用的是MySQL,所以Key generator选择identity
完成之后打开JPA的试图模式看看效果,右下有管理工具可以设置每一个对象及其里面的值
看图说话暂停,现在开始配置必要的文件,里面有说明,部分参考了rapid-framework http://code.google.com/p/rapid-framework/ 不错的胶水,强烈推荐
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" 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"> <!-- session超时定义,单位为分钟 --> <session-config> <session-timeout>10</session-timeout> </session-config> <!-- 默认首页定义 --> <welcome-file-list> <welcome-file>index.jsp</welcome-file> <welcome-file>index.html</welcome-file> </welcome-file-list> <!-- Error Page定义 --> <error-page> <error-code>500</error-code> <location>/commons/error.jsp</location> </error-page> <error-page> <error-code>404</error-code> <location>/commons/404.jsp</location> </error-page> <error-page> <error-code>403</error-code> <location>/commons/403.jsp</location> </error-page> <!-- 配置SpringMVC参数 --> <servlet> <servlet-name>StrongJPA2</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/StrongJPA2MVC.xml </param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>StrongJPA2</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping> <!-- Spring ApplicationContext配置文件的路径,可使用通配符,多个路径用,号分隔 此参数用于后面的Spring-Context loader --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.xml</param-value> </context-param> <!-- 编码过滤器 Character Encoding filter --> <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> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--Spring ApplicationContext 载入 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 使Spring支持request与session的scope,如:<bean id="loginAction" class="com.foo.LoginAction" scope="request"/> --> <listener> <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> </listener> <!-- Spring 刷新Introspector防止内存泄露 --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <!-- Enables clean URLs with JSP views e.g. /welcome instead of /app/welcome <filter> <filter-name>UrlRewriteFilter</filter-name> <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class> </filter> <filter-mapping> <filter-name>UrlRewriteFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> --> </web-app>
因为使用的是Spring的MVC,这里有两个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: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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="persistenceUnitName" value="StrongJPA2" /> <property name="loadTimeWeaver"> <bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory" /> </bean> <tx:annotation-driven transaction-manager="transactionManager" /> <context:component-scan base-package="jpa" /> <bean id="TYhDAO" class="jpa.TYhDAO"> <property name="entityManagerFactory" ref="entityManagerFactory" /> </bean> </beans>
StrongJPA2MVC.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:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <context:component-scan base-package="controller"/> <mvc:annotation-driven /> <mvc:interceptors> <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" /> </mvc:interceptors> <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" /> <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"> <property name="templateLoaderPath" value="/WEB-INF/classes/view" /> </bean> <bean id="freemarkerViewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver"> <property name="cache" value="false" /> <property name="suffix" value=".ftl" /> <property name="exposeSpringMacroHelpers" value="true" /> </bean> </beans>
persistence.xml
<?xml version="1.0" encoding="UTF-8"?> <persistence version="1.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_1_0.xsd"> <persistence-unit name="StrongJPA2" transaction-type="RESOURCE_LOCAL"> <provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider> <class>jpa.TBm</class> <class>jpa.TXw</class> <class>jpa.TXwfl</class> <class>jpa.TXx</class> <class>jpa.TYh</class> <properties> <property name="openjpa.ConnectionDriverName" value="com.mysql.jdbc.Driver" /> <property name="openjpa.ConnectionURL" value="jdbc:mysql://localhost:3306/strongword" /> <property name="openjpa.ConnectionUserName" value="root" /> <property name="openjpa.ConnectionPassword" value="123456" /> <property name="openjpa.ConnectionProperties" value="" /> <property name="openjpa.RemoteCommitProvider" value="sjvm" /> <!-- 启用缓存,并且设置缓存的容量为5000,并且禁用软引用容量 --> <property name="openjpa.DataCache" value="true(CacheSize=5000, SoftReferenceSize=0)" /> <!-- 启用查询结果缓存,缓存的容量为1000,并且软引用的容量为100 --> <property name="openjpa.QueryCache" value="CacheSize=1000, SoftReferenceSize=100" /> <!-- 启用查询结果缓存,缓存的容量为1000,并且软引用的容量为100 --> <property name="openjpa.QueryCompilationCache" value="true" /> <!-- 数据库连接工厂时的属性 QueryTimeout:JDBC驱动执行查询超时的时间,以秒为单位。 PrettyPrint:是否格式化输出SQL语句。 PrettyPrintLineLength:SQL每行输出的最大长度。 --> <property name="openjpa.Log" value="SQL=TRACE" /> <property name="openjpa.ConnectionFactoryProperties" value="PrettyPrint=true, PrettyPrintLineLength=100" /> <!-- 查询结果一次转化为对象的最多个数,相当于JDBC的结果集对象Statement.set FetchSize。默认为-1,表示所有的查询对象立即初始化;0表示使用JDBC驱动默认的数值 --> <property name="openjpa.FetchBatchSize" value="-1" /> </properties> </persistence-unit> </persistence>
完成之后就是构建DAO类了,下载包里面有不多说了,这里讲以下controller的一个问题
indexController.java
@Controller @RequestMapping("/") public class indexController extends MultiActionController { @Resource(name = "TYhDAO") private TYhDAO tyhDAO; @RequestMapping(value = "/index") public ModelAndView ChaXunXianShi(HttpServletRequest request, HttpServletResponse response, MYh model) { return new ModelAndView("/index", "model", model); } }
index.ftl
hello world <br/>${model?default("no")}<br/>${model.yhDlm?default("no")}
好了,跑起来之后访问地址 http://localhost:8080/StrongJPA2/index.html 成功,兴奋阿……,用一下DAO吧
修改indexController.java
@Controller @RequestMapping("/") public class indexController extends MultiActionController { @Resource(name = "TYhDAO") private TYhDAO tyhDAO; @RequestMapping(value = "/index") public ModelAndView ChaXunXianShi(HttpServletRequest request, HttpServletResponse response, MYh model) { List<TYh> list = tyhDAO.findAll(); System.out.println(list.get(0)); return new ModelAndView("/index", "model", list.get(0)); } }
很不幸,系统报错:
2010-3-23 9:42:23 org.apache.catalina.core.StandardWrapperValve invoke
严重: Servlet.service() for servlet StrongJPA2 threw exception
<openjpa-2.0.0-beta2-r422266:915978 nonfatal user error> org.apache.openjpa.persistence.ArgumentException: This configuration disallows runtime optimization, but the following listed types were not enhanced at build time or at class load time with a javaagent: "[class jpa.TBm, class jpa.TXwfl, class jpa.TXx, class jpa.TYh, class jpa.TXw]".
当初为这个把我郁闷的,去 OpenJPA和Spring网站翻了半天才知道tomcat启动的时候要注册一个agent,名字叫spring-agent.jar,兴奋……翻遍spring的包没找到这个东东 狂晕……,求教Google半天从一个犄角旮旯发现2.5这个包换名字,现在是org.springframework.instrument-3.0.1.RELEASE-A.jar,找到2.5的spring-agent.jar才发现本来包里面的路径名就应该是instrument。
把这个包改成spring-agent.jar(本身那个太长了),防盗tomcat/lib目录里面,然后给tomcat加上启动参数 -javaagent:/simen/workspace/tomcat/lib/spring-agent.jar,在Eclipse里面是右键点这个项目,Debug as -> Debug Configrations....
好了,结束
参考备用:http://www.oschina.net/code/explore/apache-camel-2.5.0/components/camel-jpa/pom.xml