JPA class loading issue with Hibernate

巧了我就是萌 提交于 2019-12-12 03:59:53

问题


When I am attempting to fetch an entry from my database, the type returned from the EntityManager differs from the type specified in my code. They are both com.mycompany.Foo, but they have been instanciated with two different class loaders. I have found out that the class loader for the second type has repositories set to WEB-INF/classes/ with jarPath set to /WEB-INF/lib. This is all set up using JPA with 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'
}

The class fetching the entity:

@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);
    }
}

I am compiling this using IntelliJ (Exploded web application), could it be an issue with my deployment settings? They are currently being defined by Gradle through the war plugin.


回答1:


The issue was that the libraries that loads the libraries which scans for annotated @Entity classes is not in the lib folder for my domain. Moving the dependencies for my project to this folder fixed my issue.



来源:https://stackoverflow.com/questions/32554121/jpa-class-loading-issue-with-hibernate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!