2015-09-06 2 views
1

Я видел похожие сообщения, но у меня все еще есть проблемы. Я позаботился о javax.persistence.Entity, а также о классе сопоставления в xml, но мне трудно понять этот. Помогите !!!org.hibernate.MappingException: Неизвестный объект: com.gontuseries.hibernate.Student_Info

Исключение в потоке "основного" org.hibernate.MappingException: Неизвестный объект: com.gontuseries.hibernate.Student_Info в org.hibernate.internal.SessionFactoryImpl.getEntityPersister (SessionFactoryImpl.java:776) в орг. hibernate.internal.SessionImpl.getEntityPersister (SessionImpl.java:1451) в org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId (AbstractSaveEventListener.java:100) ...

package com.gontuseries.hibernate; 

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

public class Main { 

    public static void main(String[] args) { 

     // Write the Student_Info object into the database 
     Student_Info student = new Student_Info(); 
     student.setName("Gontu"); 
     student.setRollNo(1); 

     SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); 
     Session session = sessionFactory.openSession(); 
     session.beginTransaction(); 

     // this would save the Student_Info object into the database 
     session.save(student); 

     session.getTransaction().commit(); 
     session.close(); 
     sessionFactory.close(); 
    } 
} 

package com.gontuseries.hibernate; 

import javax.persistence.Column; 

import javax.persistence.Entity; 
import javax.persistence.Id; 
import javax.persistence.Table; 

@Entity 
@Table(name="STUDENT_INFORMATION") 
public class Student_Info{ 
    @Id 
    private int rollNo; 
    @Column 
    private String name; 

    public int getRollNo() { 
     return rollNo; 
    } 
    public void setRollNo(int rollNo) { 
     this.rollNo = rollNo; 
    } 
    public String getName() { 
     return name; 
    } 
    public void setName(String name) { 
     this.name = name; 
    } 


} 

package com.gontuseries.hibernate; 

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


public class HibernateUtil { 

    private static final SessionFactory sessionFactory = buildSessionFactory(); 
    private static ServiceRegistry serviceRegistry; 

    private static SessionFactory buildSessionFactory() { 

     try { 
      Configuration configuration = new Configuration(); 
      configuration.configure(); 

      serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
        configuration.getProperties()).build(); 

      return configuration.buildSessionFactory(serviceRegistry); 

     } catch (Throwable ex) { 

      System.err.println("Failed to create sessionFactory object." + ex); 
      throw new ExceptionInInitializerError(ex); 
     } 
    } 

    public static SessionFactory getSessionFactory() { 

     return sessionFactory; 
    } 
} 

<?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:3306/hibernateTutorials</property> 
     <property name="connection.username">root</property> 
     <property name="connection.password"></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> 

     <!-- 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 the existing tables and create new one --> 
     <property name="hbm2ddl.auto">create</property> 

     <!-- Mention here all the model classes along with their package name --> 
     <mapping class="com.gontuseries.hibernate.Student_Info"/> 


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

Я очистил свой вопрос на некоторые из них. Включение сообщений об ошибках в комментарии полезно. Для получения дополнительной информации об уценке вы можете обратиться к [редактированию справки] (http://stackoverflow.com/editing-help) – Machavity

ответ

2

у меня то же самое вопрос. И только добавление

configuration.addAnnotatedClass(User.class); 

в классе HibernateUtil помог мне. Но я не думаю, что это правильный способ добавления классов, он должен работать, добавляя файл hibernate.cfg.xml, но это не так.

0

Это сработало для меня (для hibernate 5.1.0 jar) Я следил за http://www.gontu.org/hibernate-framework-tutorials/ и имел такую ​​же ошибку.

import org.hibernate.SessionFactory; 
import org.hibernate.boot.MetadataSources; 
import org.hibernate.boot.registry.StandardServiceRegistry; 
import org.hibernate.boot.registry.StandardServiceRegistryBuilder; 

public class HibernateUtil { 

// A SessionFactory is set up once for an application! 
    final static StandardServiceRegistry registry = new StandardServiceRegistryBuilder() 
      .configure() // configures settings from hibernate.cfg.xml 
      .build(); 
    private static SessionFactory sessionFactory=null; 

private static SessionFactory buildSessionFactory() { 

    try { 
     sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory(); 
     return sessionFactory; 
    } 
    catch (Exception e) { 
     // The registry would be destroyed by the SessionFactory, but we had trouble building the SessionFactory 
     // so destroy it manually. 
     StandardServiceRegistryBuilder.destroy(registry); 
     throw new ExceptionInInitializerError(e); 
    } 

} 

public static SessionFactory getSessionFactory() { 
    if(sessionFactory==null){ 
     buildSessionFactory(); 
    } 
    return sessionFactory; 
} 

}

Смежные вопросы