【问题标题】:Error: Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.hibernate.demo.model.Contact错误:线程“主”org.hibernate.MappingException 中的异常:未知实体:com.hibernate.demo.model.Contact
【发布时间】:2016-07-05 12:46:21
【问题描述】:

在将其标记为重复之前,请阅读以下内容:

我已经尝试过类似问题中的所有给定答案-

  1. 我对@Entity 的导入是正确的:import javax.persistence.Entity;
  2. 存在 hibernate.cfg.xml 中实体的映射
  3. 类是从 pkg 级别映射的:“com.hibernate.demo.model.Contact”
  4. AnnotationConfiguration 也无法解决问题。
  5. 也尝试了所有其他第二到第三的最佳答案。

背景:我创建了一个 Spring-boot 项目,我正在尝试学习休眠,我正在使用 H2 db,我正面临 >未知实体:com.hibernate.demo.model.Contact

我已验证该课程的 mapping 存在于 hibernate.cfg.xml

<mapping class="com.hibernate.demo.model.Contact"/>

我还验证了映射具有完整的 pkg 级别映射路径

这是我的 hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>

<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

        <!-- Database connection settings -->
        <property name="connection.driver_class">org.h2.Driver</property>
        <property name="connection.url">jdbc:h2:./data/contactmgr</property>


        <property name="connection.username">sa</property>


        <property name="hibernate.default_schema">PUBLIC</property>

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

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

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.internal.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">create</property>

        <property name="show_sql">true</property>

        <mapping class="com.hibernate.demo.model.Contact"/>

    </session-factory>

</hibernate-configuration>

我的 Application.java 主类:-

package com.hibernate.demo;



import java.io.IOException; import java.io.RandomAccessFile; import java.nio.channels.FileLock;

import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry;

import com.hibernate.demo.model.Contact;

public class Application {

    //Session factory
    private static final SessionFactory sessionFactory = buildSesssionFactory();

      public static void main(String[] args) throws Exception {

        System.out.println("Session factory");
        Contact contact = new Contact.ContactBuilder("Bob", "Marley").withEmail("bob.nik@gmail.com").withPhone(5859789733L).build();

        //Open a Session
        System.out.println("Open a Session");
        Session session = sessionFactory.openSession();

        //Begin a Transaction
        System.out.println("Begin a Transaction");
         session.beginTransaction();


        //Use the session to save the contact
        System.out.println("Use the session to save the contact");
        try{
        session.save(contact);
        } catch(Exception e) {
            // Close the session
            shutdown();
            throw e;

        }
        //Commit the transaction
        System.out.println("Commit the transaction");
        session.getTransaction().commit();


        // Close the session
        System.out.println("Close the session");
        session.close();

    }

   private static SessionFactory buildSessionFactory()
   {

      try
      {
         if (sessionFactory == null)
         {
            Configuration configuration = new Configuration().configure(Application.class.getResource("/hibernate.cfg.xml"));
            StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
            serviceRegistryBuilder.applySettings(configuration.getProperties());
            ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
         }
         return sessionFactory;
      } catch (Throwable ex)
      {
         System.err.println("Initial SessionFactory creation failed." + ex);
         throw new ExceptionInInitializerError(ex);
      }
   }

   public static SessionFactory getSessionFactory()
   {
      return sessionFactory;
   }

   public static void shutdown()
   {
      getSessionFactory().close();
   }

}

我正在做所有正确的事情,我已经检查过

@Entity 导入有正确的包

package com.hibernate.demo.model;

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

@Entity
public class Contact {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column
    private String firstName;

    @Column
    private String lastName;

    @Column
    private String email;

    @Column
    private Long phone;

    public Contact() {
    }

    public Contact(ContactBuilder contactBuilder) {
        this.firstName = contactBuilder.firstName;
        this.lastName = contactBuilder.lastName;
        this.email = contactBuilder.email;
        this.phone=contactBuilder.phone;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = 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 getPhone() {
        return phone;
    }

    public void setPhone(Long phone) {
        this.phone = phone;
    }

    @Override
    public String toString() {
        return "Contact [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email
                + ", phone=" + phone + "]";
    }

    public static class ContactBuilder {

        private String firstName;

        private String lastName;

        private String email;

        private Long phone;

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

        public ContactBuilder withEmail(String email) {
            this.email = email;
            return this;

        }

        public ContactBuilder withPhone(Long phone) {
            this.phone = phone;
            return this;

        }

        public Contact build() {

            return new Contact(this);
        }

    }

}

【问题讨论】:

  • 使用注解时hibernate.cfg.xml中是否需要&lt;mapping class="..."/&gt;
  • 是的,我正在查看其他示例,他们也做了同样的事情。
  • 我找到了一个例子,这个标签没有被使用:tutorialspoint.com/hibernate/hibernate_annotations.htm
  • 我正在从teamtreehouse.com 学习hibernate,他们就是这样做的:(
  • @Shek : 在你的模型类上使用“@Table”注解并尝试

标签: java hibernate spring-boot hibernate-mapping


【解决方案1】:
configuration.addAnnotatedClass(Contact.class); 

解决了这个问题,这很奇怪,因为它意味着

<mapping class="com.contact.model.Contact"/>

不是为你做的。反正我也不喜欢 xml 配置,别管了。

【讨论】:

    猜你喜欢
    • 2016-01-16
    • 1970-01-01
    • 2016-06-09
    • 2016-03-01
    • 2017-06-03
    • 2023-03-19
    • 1970-01-01
    • 2012-02-19
    • 2014-09-01
    相关资源
    最近更新 更多