Весна + JPA + DAO + Tomcat - PullRequest
       20

Весна + JPA + DAO + Tomcat

0 голосов
/ 18 августа 2011

persistence.xml

<persistence-unit name="myEntityManager" transaction-type="RESOURCE_LOCAL">
<class>com.epam.testapp.model.News</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>

Новости

private Integer newsId;
private String title;
private String brief;
private String content;
private Date created;
private String dateCreatedString;

public News() {
}

@Id
@Column(name = "NEWS_ID")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "news_seq")
@SequenceGenerator(name = "news_seq", sequenceName = "NEWS_SEQ")
public Integer getNewsId() {
    return newsId;
}

public void setNewsId(Integer newsId) {
    this.newsId = newsId;
}

@Column(nullable = false, name = "TITLE")
public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

@Column(nullable = false, name = "BRIEF")
public String getBrief() {
    return brief;
}

public void setBrief(String brief) {
    this.brief = brief;
}

@Column(name = "CONTENT")
public String getContent() {
    return content;
}

public void setContent(String content) {
    this.content = content;
}

@Temporal(value = TemporalType.DATE)
@Column(nullable = false, name = "CREATED")
public Date getCreated() {
    return created;
}

public void setCreated(Date created) {
    this.created = created;
}

@Transient
public String getDateCreatedString() {
    return dateCreatedString;
}

public void setDateCreatedString(String dateCreatedString) {
    this.dateCreatedString = dateCreatedString;
} 

равно и хеш-код

xml для весны

    <bean id="propertyConfigurer"
      class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" value="/WEB-INF/databaseConfiguration.properties"/>
</bean>

<bean  id="newsDAO"
    class="com.epam.testapp.database.NewsDaoJPA"> 
    <property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>


<bean id="entityManagerFactory" class=
  "org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter">
            <property name="showSql" value="true"/>     
            <property name="database" value="ORACLE"/>
        </bean>
    </property>
    <property name="loadTimeWeaver">
        <bean class="org.springframework.instrument.classloading.SimpleLoadTimeWeaver"/>
    </property>
</bean>

<bean id="dataSource" 
 class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${database.driver}"/>
    <property name="url" value="${database.url}"/>
    <property name="username" value="${database.user}"/>
    <property name="password" value="${database.password}"/>
</bean>

<bean id="transactionManager" 
 class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory"/>
    <property name="dataSource" ref="dataSource"/>
</bean>

но когда вызывать метод дао например

public List<News> getList() throws DAOException {
    return getJpaTemplate().find("select n from News n");
}

я получаю

java.lang.IllegalArgumentException: object is not an instance of declaring class
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.invokeProxyMethod(AbstractEntityManagerFactoryBean.java:423)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean$ManagedEntityManagerFactoryInvocationHandler.invoke(AbstractEntityManagerFactoryBean.java:485)
at $Proxy4.createEntityManager(Unknown Source)
at org.springframework.orm.jpa.EntityManagerFactoryAccessor.createEntityManager(EntityManagerFactoryAccessor.java:116)
at org.springframework.orm.jpa.JpaTemplate.execute(JpaTemplate.java:176)
at org.springframework.orm.jpa.JpaTemplate.contains(JpaTemplate.java:245)
at com.epam.testapp.database.NewsDaoJPA.getList(NewsDaoJPA.java:26)
at com.epam.testapp.presentation.action.NewsAction.list(NewsAction.java:95)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:269)
at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:170)
at org.apache.struts.actions.LookupDispatchAction.execute(LookupDispatchAction.java:146)
at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:425)
at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:228)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:449)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at com.epam.testapp.utils.filter.EncodingFilter.doFilter(EncodingFilter.java:45)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:394)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)

Есть идеи?

1 Ответ

1 голос
/ 18 августа 2011

Ваш loadTimeWeaver - это SimpleLoadTimeWeaver, который обычно используется в средах тестирования.Из javadocs

LoadTimeWeaver, который создает и предоставляет SimpleInstrumentableClassLoader.

В основном предназначен для сред тестирования, где достаточно выполнить все преобразования классов для новогосоздал экземпляр ClassLoader.

В соответствии с этой записью в руководстве по Spring JPA, я подозреваю, вам понадобится что-то вроде этого:

<context:load-time-weaver/>
<bean id="entityManagerFactory"
      class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter">
            <property name="showSql" value="true"/>     
            <property name="database" value="ORACLE"/>
        </bean>
    </property>
</bean>

ивам согласно этому может потребоваться изменить контекст tomcat, чтобы сказать tomcat использовать пользовательский загрузчик классов:

<Context path="/myWebApp" docBase="/my/webApp/location">
    <Loader loaderClass="org.springframework.instrument.classloading.tomcat.TomcatInstrumentableClassLoader"/>
</Context>
...