Java org.hibernate.MappingException:未知实体:annotations.Users

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23214454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 21:22:38  来源:igfitidea点击:

org.hibernate.MappingException: Unknown entity: annotations.Users

javahibernateexceptionentity

提问by JAN

Consider the hierarchy :

考虑层次结构:

enter image description here

在此处输入图片说明

And the following classes and xml :

以及以下类和 xml :

HibernateUtil.java

HibernateUtil.java

package annotations;

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


/**
 * 
 * @author X3
 *
 */
public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();
    private static final String HIBERNATE_CFG = "hibernateAnnotations.cfg.xml";

    private static SessionFactory buildSessionFactory() 
    {
        Configuration cfg = new Configuration().addResource(HIBERNATE_CFG).configure();
        ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().
                applySettings(cfg.getProperties()).buildServiceRegistry();
        SessionFactory sessionFactory = cfg.buildSessionFactory(serviceRegistry);
        return sessionFactory;
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

Users.java

用户.java

package annotations;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.sql.Timestamp;

@Entity
@Table(name = "Users")
public class Users {

    @Id
    @GeneratedValue
    @Column(name = "USER_ID")
    private long userID;

    @Column(name = "USERNAME", nullable = false, length = 100)
    private String username;

    @Column(name = "MessageTimeDate", nullable = false)
    private java.sql.Timestamp datetime;

    @Column(name = "UserMessage", nullable = false)
    private String message;



    public Users(String username , String message)
    {
        java.util.Date date = new java.util.Date();
        this.datetime = new Timestamp(date.getTime());

        this.username = username;
        this.message = message;
    }

    public long getUserID() {
        return userID;
    }

    public void setUserID(long userID) {
        this.userID = userID;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public java.sql.Timestamp getDatetime() {
        return datetime;
    }

    public void setDatetime(java.sql.Timestamp datetime) {
        this.datetime = datetime;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

}

Main.java

主程序

package annotations;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class Main {

    public static void main(String[] args) {

        try
        {
               SessionFactory sf = HibernateUtil.getSessionFactory();
               Session session = sf.openSession();
               session.beginTransaction();

               Users user1 = new Users("Hyman" , "Hello");
               session.save(user1);
               session.getTransaction().commit();
               session.close();
        }

        catch (Exception e)
        {
            System.out.println(e.toString());
            e.getStackTrace();
        }


    }
}

And hibernateAnnotations.cfg.xml

hibernateAnnotations.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>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/CHAT_DB</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
        <property name="connection.pool_size">1</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="current_session_context_class">thread</property>
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">create</property>
        <mapping class="annotations.Users"></mapping>       
    </session-factory>
</hibernate-configuration>

When I run main(), the following error appears in output window :

当我运行 main() 时,输出窗口中出现以下错误:

org.hibernate.MappingException: Unknown entity: annotations.Users

But the entity Usersis in annotationspackage , so what's wrong ?

但是实体Usersannotationspackage 中,有什么问题?

采纳答案by Asif Bhutto

The Hibernate configuration file must define the entity classes:

Hibernate 配置文件必须定义实体类:

<mapping class="annotations.Users"/>

Or you must explicitly add the class to the configuration using

或者您必须使用显式将类添加到配置中

configuration.addClass(annotations.Users.class)
// Read mappings as a application resourceName
 // addResource is for add hbml.xml files in case of declarative approach
configuration.addResource("myFile.hbm.xml");  // not hibernateAnnotations.cfg.xml

回答by user2247545

Add the following to your xml:

将以下内容添加到您的 xml:

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan">
        <list>
            <value>annotations</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
        </props>
    </property>
</bean>

<tx:annotation-driven transaction-manager="transactionManager" />

<bean id="transactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

回答by Marvo

For those using Spring's Java configuration classes, you might write the following:

对于那些使用 Spring 的 Java 配置类的人,您可以编写以下内容:

@Autowired
@Bean(name = "sessionFactory")
public SessionFactory getSessionFactory(DataSource dataSource) {
    LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
    sessionBuilder.addProperties(getHibernateProperties());
    sessionBuilder.addAnnotatedClasses(Foo.class);
    sessionBuilder.addAnnotatedClasses(Bar.class);
    sessionBuilder.addAnnotatedClasses(Bat.class);
    return sessionBuilder.buildSessionFactory();
}

回答by user2148060

Define the Entityclass in Hibernate.cfg.xml

EntityHibernate.cfg.xml 中定义类

<mapping class="com.supernt.Department"/>

While creating the sessionFactoryobject Load the Configurationfile Like

在创建sessionFactory对象时加载配置文件

SessionFactory factory = new AnnotationConfiguration().configure("hibernate.cfg.xml").buildSessionFactory();

回答by user5728489

When I was trying to rewrite my example (from tutorialspoint) to use annotations, I got the same exception. This helped me (addAnnotatedClass()):

当我尝试重写我的示例(来自tutorialspoint)以使用注释时,我遇到了同样的异常。这对我有帮助(addAnnotatedClass()):

Configuration cfg=new Configuration(); 
cfg.addAnnotatedClass(com.tutorialspoint.hibernate.entity.Employee.class);
cfg.configure();

回答by Shobhit Srivastava

I was having same problem.

我遇到了同样的问题。

Use @javax.persistence.Entityinstead of org.hibernate.annotations.Entity

使用@javax.persistence.Entity代替org.hibernate.annotations.Entity

回答by Ishaq

Problem occurs because of the entry mapping class="annotations.Users"in hibernate.cfg.xmlremove that line then it will be work.

由于删除该行中的条目mapping class="annotations.Users"而出现问题hibernate.cfg.xml,然后它将起作用。

I had the same issue. When I removed the above line then it was working fine for me.

我遇到过同样的问题。当我删除上面的行时,它对我来说工作正常。

回答by Narendra Rawat

Instead of using HibernateUtil.java, to create sessionfactory object, you should use this:

而不是使用 HibernateUtil.java 来创建 sessionfactory 对象,你应该使用这个:

SessionFactory sessionFactory=new AnnotationConfiguration().configure().buildSessionFactory();

Because in order to avoid the exception, you'll have to declare the class object in HibernateUtil.java file as configuration.addAnnotatedClass(Student_Info.class);which looks dumb because we have provided the entry already in hibernate.cfg.xml file.

因为为了避免异常,您必须在 HibernateUtil.java 文件中声明类对象,configuration.addAnnotatedClass(Student_Info.class);因为我们已经在 hibernate.cfg.xml 文件中提供了该条目。

To use the AnnotationConfiguration class you'll have to add a jar to your project build path: http://www.java2s.com/Code/Jar/h/Downloadhibernate353jar.htm

要使用 AnnotationConfiguration 类,您必须在项目构建路径中添加一个 jar:http: //www.java2s.com/Code/Jar/h/Downloadhibernate353jar.htm

回答by Mithun Debnath

 public static void main(String[] args) {
      try{
        // factory = new Configuration().configure().buildSessionFactory();
         factory = new AnnotationConfiguration().
                   configure().
                   //addPackage("com.xyz") //add package if used.
                   addAnnotatedClass(Employee.class).
                   buildSessionFactory();
      }catch (Throwable ex) { 
         System.err.println("Failed to create sessionFactory object." + ex);
         throw new ExceptionInInitializerError(ex); 
      }//you can write like this in your test class inside main method.this way you will be able to do the things using annotaions only

回答by Sandy

Add the following code to hibernate.cfg.xml

将以下代码添加到 hibernate.cfg.xml

  <property name="hibernate.c3p0.min_size">5</property>
  <property name="hibernate.c3p0.max_size">20</property>
  <property name="hibernate.c3p0.timeout">300</property>
  <property name="hibernate.c3p0.max_statements">50</property>
  <property name="hibernate.c3p0.idle_test_period">3000</property>