Hibernate未知实体(不缺少@Entity或导入javax.persistence.Entity)

时间:2012-04-02 17:05:20

标签: java hibernate

我有一个非常简单的课程:

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "users")
public class User {

    @Column(name = "firstName")
    private String firstName;

    @Column(name = "lastName")
    private String lastName;

    @Column(name = "email")
    private String email;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name = "id")
    private long id;


    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
}

我用这个主要来称呼它:

public class Main {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        HibernateUtil.buildSessionFactory();
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        User u = new User();
        u.setEmail("david@hello.co.uk");
        u.setFirstName("David");
        u.setLastName("Gray");

        session.save(u);
        session.getTransaction().commit();
        System.out.println("Record committed");
        session.close();


    }

}

我一直收到这个MappingException:

Exception in thread "main" org.hibernate.MappingException: Unknown entity: org.assessme.com.entity.User
    at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:1172)
    at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1316)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:117)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:204)
    at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:189)
    at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
    at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:670)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:662)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:658)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:352)
    at $Proxy4.save(Unknown Source)
    at Main.main(Main.java:20)

我的HibernateUtil是:

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtil {

    private static SessionFactory sessionFactory;
    private static ServiceRegistry serviceRegistry;

    public static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            Configuration configuration = new Configuration();
            configuration.configure();
            serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();     
            return new Configuration().configure().buildSessionFactory(serviceRegistry);
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        sessionFactory = new Configuration().configure().buildSessionFactory(serviceRegistry);
        return sessionFactory;
    }

}

有没有人有任何想法,因为我看了很多重复,但决议似乎并不适合我。这是我的hibernate.cfg.xml:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost/ssme</property>
        <property name="connection.username">root</property>
        <property name="connection.password">mypassword</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">update</property>

    </session-factory>
</hibernate-configuration>

7 个答案:

答案 0 :(得分:16)

您应该使用AnnotationConfiguration代替Configuration,然后致电

configuration.addAnnotatedClass(User.class);

将您的类添加到映射类列表中。

答案 1 :(得分:14)

hibernate.cfg.xml之前添加到</session-factory>

<mapping class="org.assessme.com.entity.User" />

答案 2 :(得分:4)

考虑使用AnnotationConfiguration描述here

您可以使用其addClass(User.class)方法,也可以使用addPackage("org.assessme.com.entity")方法保留多个实体。

你正在用这个HibernateUtil课重新发明轮子。考虑使用Spring,这样你就可以利用它的AnnotationSessionFactoryBean

答案 3 :(得分:2)

您有persistence.xml还是hibernate.cfg.xml?如果你必须在其中添加你的映射类,那么hibernate会理解你的类正在映射到数据库。如果您有hibernate.cfg.xml,可以像这样添加

<mapping class="com.entity.Users"/>

答案 4 :(得分:2)

我忘了将hbm.xml映射添加到我的cfg.xml文件中。一旦我添加它,这个异常就消失了。

<mapping resource="com/mycompany/backend/hibernate/CServiceCenters.hbm.xml" />

答案 5 :(得分:2)

将以下行添加到您的hibernate.cfg.xml

<mapping class="fully qualified Entity class name"/>

答案 6 :(得分:0)

我也遇到了类似的问题,但是当我在方言中附加 MySQL 版本时它得到了解决。 org.hibernate.dialect.MySQL8Dialect

似乎是兼容性问题。