使用OpenJPA+Spring组合,初始化OpenJPA组件时发生如下错误:
29891 jpaOpenJpaPersistenceUnit INFO [http-8080-1] openjpa.Runtime - Starting OpenJPA 1.2.1 32094 jpaOpenJpaPersistenceUnit TRACE [http-8080-1] openjpa.jdbc.SQL - <t 2939216, conn 7291773> executing prepstmnt 5119087 SELECT SEQUENCE_SCHEMA, SEQUENCE_NAME FROM INFORMATION_SCHEMA.SYSTEM_SEQUENCES 32110 jpaOpenJpaPersistenceUnit TRACE [http-8080-1] openjpa.jdbc.SQL - <t 2939216, conn 7291773> [16 ms] spent 32125 jpaOpenJpaPersistenceUnit TRACE [http-8080-1] openjpa.jdbc.SQL - <t 2939216, conn 28358933> executing stmnt 24528146 CREATE TABLE OPENJPA_SEQUENCE_TABLE (ID TINYINT NOT NULL, SEQUENCE_VALUE BIGINT, PRIMARY KEY (ID)) 32125 jpaOpenJpaPersistenceUnit TRACE [http-8080-1] openjpa.jdbc.SQL - <t 2939216, conn 28358933> [0 ms] spent 32125 jpaOpenJpaPersistenceUnit TRACE [http-8080-1] openjpa.jdbc.SQL - <t 2939216, conn 22877561> executing stmnt 13663107 CREATE TABLE t_user (id INTEGER NOT NULL, password VARCHAR(255), username VARCHAR(255), PRIMARY KEY (id)) 32125 jpaOpenJpaPersistenceUnit TRACE [http-8080-1] openjpa.jdbc.SQL - <t 2939216, conn 22877561> [0 ms] spent java.lang.ClassNotFoundException: org.apache.openjpa.enhance.InstrumentationFactory at java.net.URLClassLoader$1.run(URLClassLoader.java:200) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:307) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at java.lang.ClassLoader.loadClass(ClassLoader.java:252) at sun.instrument.InstrumentationImpl.loadClassAndStartAgent(InstrumentationImpl.java:280) at sun.instrument.InstrumentationImpl.loadClassAndCallAgentmain(InstrumentationImpl.java:348)
Spring配置文件如下:
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" p:dataSource-ref="dataSource" p:persistenceUnitName="jpaOpenJpaPersistenceUnit"> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter" p:showSql="true" p:generateDdl="true" p:database="HSQL" /> </property> <property name="loadTimeWeaver"> <bean class="org.springframework.instrument.classloading.SimpleLoadTimeWeaver"/> </property> </bean>
解决的办法如下:
修改Spring配置:
<property name="loadTimeWeaver">
<!--
<bean class="org.springframework.instrument.classloading.SimpleLoadTimeWeaver"/>
-->
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
</property>
拷贝spring下spring-agent.jar包至tomcat的lib下,给tomcat服务器启动脚本中追加如下代码:
例如:修改tomcat的bin下startup.bat文件:
......
if exist "%CATALINA_HOME%/bin/catalina.bat" goto okHome
cd ..
set CATALINA_HOME=%cd%
set JAVA_OPTS="-javaagent:%CATALINA_HOME%/lib/spring-agent.jar"
cd %CURRENT_DIR%
:gotHome
......
如果使用Eclipse等IDE,需要在Eclipse的配置中给Tomcat启动追加javaagent。
例如:MyEclipse中:
至此启动Tomcat访问服务,上述错误解决。