Gradle Hibernate配置需要映射类

时间:2015-04-14 20:17:35

标签: java hibernate jpa orm gradle

我正在使用Gradle来管理Hibernate的依赖项(我之前使用的是Maven),但我遇到了一些奇怪的事情。当我尝试将带注释的类的一个简单实例保存到数据库时,我最终得到一个MappingException,说该类没有被映射。由于我存储实例的方式,这种情况有点独特。假设情况是这样的:我有一个正确注释的hibernate类,它将使用Session使用EntityManager使用saveOrUpdate()进行保存。我有一个persistance.xml,但没有hibernate配置文件。我依靠EntityManager自动检测映射类来将其提供给Session,因此可以将其识别为正确注释。我正在使用Hibernate 4.3.8。代码在切换之前工作。所有方法调用都在事务上下文中进行,并且提交事务并刷新会话。

例外:

Caused by: org.hibernate.MappingException: Unknown entity: com.gmail.sarah.project.Rank

Gradle Dependencies:

compile "org.hibernate:hibernate-core:4.3.8.Final"
compile "org.hibernate:hibernate-entitymanager:4.3.8.Final"
compile "org.hibernate:hibernate-ehcache:4.3.8.Final"
compile "mysql:mysql-connector-java:5.1.35"

编辑(测试用例也有同样的问题): 主类:

package com.gmail.physicistsarah.gradletestproject.core;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Table;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class Init {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    EntityManagerFactory factory = Persistence.createEntityManagerFactory("Test_Project");
    EntityManager manager = factory.createEntityManager();
    Session session = manager.unwrap(Session.class);
    Transaction transaction = session.getTransaction();
    transaction.begin();
    session.saveOrUpdate(new Person("Carl", "Gauss"));
    session.saveOrUpdate(new Person("Benoit", "Mandelbrot"));
    transaction.commit();
    factory.close();
}

@Entity
@Table(name = "Person")
public static class Person {

    @Column(name = "First_Name", nullable = false)
    private final String firstName;
    @Column(name = "Last_Name", nullable = false)
    private final String lastName;

    public Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
}

} 的persistence.xml:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="Test_Project" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <properties>
        <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/test_project_db?zeroDateTimeBehavior=convertToNull"/>
        <property name="javax.persistence.jdbc.user" value="root"/>
        <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
        <property name="javax.persistence.jdbc.password" value=""/>
        <property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
        <property name="javax.persistence.schema-generation.database.action" value="create"/>
    </properties>
</persistence-unit>

的build.gradle:

apply plugin: 'java'
apply plugin:'application'

sourceCompatibility = '1.8'
[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'

// NetBeans will automatically add "run" and "debug" tasks relying on the
// "mainClass" property. You may however define the property prior executing
// tasks by passing a "-PmainClass=<QUALIFIED_CLASS_NAME>" argument.
//
// Note however, that you may define your own "run" and "debug" task if you
// prefer. In this case NetBeans will not add these tasks but you may rely on
// your own implementation.
mainClassName = "com.gmail.physicistsarah.gradletestproject.core.Init"
if (!hasProperty('mainClass')) {
ext.mainClass = 'com.gmail.physicistsarah.gradletestproject.core.Init'
}
task sourcesJar(type: Jar, dependsOn: classes) {
classifier = 'sources'
from sourceSets.main.allSource
}

task javadocJar(type: Jar, dependsOn: javadoc) {
classifier = 'javadoc'
from javadoc.destinationDir
}

artifacts {
archives sourcesJar
archives javadocJar
}
repositories {
mavenCentral()
// You may define additional repositories, or even remove "mavenCentral()".
// Read more about repositories here:
//   http://www.gradle.org/docs/current/userguide/dependency_management.html#sec:repositories
}

dependencies {
// TODO: Add dependencies here ...
// You can read more about how to add dependency here:
//   http://www.gradle.org/docs/current/userguide/dependency_management.html#sec:how_to_declare_your_dependencies
compile "org.hibernate:hibernate-core:4.3.8.Final"
compile "org.hibernate:hibernate-entitymanager:4.3.8.Final"
compile "org.hibernate:hibernate-ehcache:4.3.8.Final"
compile "mysql:mysql-connector-java:5.1.35"
testCompile group: 'junit', name: 'junit', version: '4.10'
}

例外:

INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.gmail.physicistsarah.gradletestproject.core.Init$Person
at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:1096)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1443)
at org.hibernate.engine.internal.ForeignKeys.isTransient(ForeignKeys.java:242)
at org.hibernate.event.internal.AbstractSaveEventListener.getEntityState(AbstractSaveEventListener.java:511)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:100)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSaveOrUpdate(SessionImpl.java:684)
at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:676)
at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:671)
at com.gmail.physicistsarah.gradletestproject.core.Init.main(Init.java:23)

persistence.xml(和META-INF包)位于resources / main文件夹中。

1 个答案:

答案 0 :(得分:1)

您的代码中有很多错误:

  1. 实体可能不是嵌套类
  2. 实体必须具有无参数构造函数
  3. 实体字段可能不是最终字段
  4. 实体必须具有使用@Id
  5. 注释的属性
  6. 实体必须列在persistence.xml文件中:

    <class>com.foo.bar.EntityClassName</class>