使用Hibernate的JPA类加载问题

时间:2015-09-13 20:15:44

标签: java hibernate java-ee jpa intellij-idea

当我尝试从数据库中获取条目时,EntityManager返回的类型与我的代码中指定的类型不同。它们都是com.mycompany.Foo,但是它们已经被两个不同的类加载器实例化了。我发现第二种类的类加载器将存储库设置为WEB-INF / classes /,并将jarPath设置为/ WEB-INF / lib。 这都是使用JPA和Hibernate设置的。

的persistence.xml:

<persistence 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"
             version="2.0">
    <persistence-unit name="manager1" transaction-type="JTA">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <jta-data-source>devResource</jta-data-source>
        <validation-mode>CALLBACK</validation-mode>
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
            <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
            <property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.SunOneJtaPlatform" />
        </properties>
    </persistence-unit>
</persistence>

build.gradle with dependencies:

group 'testApplication'
version '1.0-SNAPSHOT'

apply plugin: 'java'
apply plugin: 'war'

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.11'
    compile 'javax:javaee-api:7.0'
    compile 'org.hibernate:hibernate-entitymanager:4.3.5.Final'
    compile 'org.hibernate.javax.persistence:hibernate-jpa-2.0-api:1.0.0.Final'
    compile 'mysql:mysql-connector-java:5.1.36'
}

获取实体的类:

@Stateless
public class FooService {

    @PersistenceContext
    private EntityManager em;

    public Foo getFooEntity(final int id) {
        // Will throw a CastException since Foo is not Foo (loaded through different class loaders)
        return em.find(Foo.class, id);
    }
}

我正在使用IntelliJ(爆炸式网络应用程序)编译它,这可能是我的部署设置的问题吗?它们目前由Gradle通过war插件定义。

1 个答案:

答案 0 :(得分:0)

问题是加载扫描带注释的@Entity类的库的库不在我的域的lib文件夹中。将项目的依赖项移动到此文件夹修复了我的问题。