简体   繁体   English

将对象保存到数据库时发生Hibernate Unknown Entity异常

[英]Hibernate Unknown Entity exception when saving object to database

I've been trying to work with hibernate to read and write to a mysql database, but I keep getting a Unknown entity error when I attempt session.save() to save a Dept object to the dept mysql table. 我一直在尝试与hibernate一起读取和写入mysql数据库,但是当我尝试使用session.save()将Dept对象保存到dept mysql表中时,始终收到Unknown实体错误。 I've been looking for days for a solution and I have tried many different things, including annotating my code, changing the mapping xml file, the hibernate config xml file, etc. Most of the other people getting this error are using spring but I am not, so a lot of the other answers arent applicable. 我一直在寻找解决方案的日子,我尝试了许多不同的事情,包括注释我的代码,更改映射xml文件,休眠配置xml文件等。大多数其他遇到此错误的人都在使用spring,但是我不是,所以很多其他答案都没有。 I feel like theres something small that I'm missing. 我觉得我缺少一些小东西。

Launcher Class: 启动器类别:

final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
                .configure() // configures settings from hibernate.cfg.xml
                .build();
        try {
            SessionFactory sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory();

            System.out.println("sessionfactory made, now creating session");
            Session session = sessionFactory.openSession();
            System.out.println("made session");
            session.beginTransaction();
            System.out.println("making first dept");
            session.save( new Dept(1, "Math",  "CORE"));
            session.save( new Dept(2, "Science", "CORE"));
            System.out.println("commiting transaction");
            session.getTransaction().commit();
            session.close();
            System.out.println("SUCCESS");
        }
        catch (Exception e) {
            // The registry would be destroyed by the SessionFactory, but we had trouble building the SessionFactory
            // so destroy it manually.
            e.printStackTrace();
            StandardServiceRegistryBuilder.destroy( registry );
            System.out.println("exception, destroyed registry");
        }

Dept.java: Dept.java:

package org.myschool.timeline.Timeline_App.domain;
// Generated Jan 16, 2016 1:48:30 AM by Hibernate Tools 4.3.1.Final

import java.util.HashSet;
import java.util.Set;

/**
 * Dept generated by hbm2java
 */
public class Dept implements java.io.Serializable {

    private int deptId;
    private String name;
    private String type;
    private Set<Course> courses = new HashSet<Course>(0);

    public Dept() {
    }

    public Dept(int deptId, String name, String type) {
        this.deptId = deptId;
        this.name = name;
        this.type = type;
    }

    public Dept(int deptId, String name, String type, Set<Course> courses) {
        this.deptId = deptId;
        this.name = name;
        this.type = type;
        this.courses = courses;
    }
    //Getters and Setters cut for brevity
}

hibernate.cfg.xml: 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>
        <property name="hibernate.bytecode.use_reflection_optimizer">false</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.password">pass</property>
        <property name="hibernate.connection.url">jdbc:mysql://serverip</property>
        <property name="hibernate.connection.username">user</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.search.autoregister_listeners">false</property>
        <property name="hibernate.validator.apply_to_ddl">false</property>
        <property name="current_session_context_class">thread</property>
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
        <mapping resource="org/myschool/timeline/Timeline_App/domain/Admin.hbm.xml" />
        <mapping resource="org/myschool/timeline/Timeline_App/domain/Course.hbm.xml" />
        <mapping resource="org/myschool/timeline/Timeline_App/domain/Teacher.hbm.xml" />
        <mapping resource="org/myschool/timeline/Timeline_App/domain/Dept.hbm.xml" />
        <mapping resource="org/myschool/timeline/Timeline_App/domain/Student.hbm.xml" />
    </session-factory>
</hibernate-configuration>

And Dept.hbm.xml: 和Dept.hbm.xml:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Jan 16, 2016 1:52:21 AM by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
    <class name="org.myschool.timeline.Timeline_App.domain.Dept" table="DEPT">
        <id name="deptId" type="int">
            <column name="DEPTID" />
            <generator class="assigned" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="NAME" />
        </property>
        <property name="type" type="java.lang.String">
            <column name="TYPE" />
        </property>
        <set name="courses" table="COURSE" inverse="false" lazy="true">
            <key>
                <column name="DEPTID" />
            </key>
            <one-to-many class="org.myschool.timeline.Timeline_App.domain.Course" />
        </set>
    </class>
</hibernate-mapping>

This is the error I get when i launch: 这是我启动时遇到的错误:

making first dept
org.hibernate.MappingException: Unknown entity: org.myschool.timeline.Timeline_App.domain.Dept
    at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:1096)
    at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1479)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:117)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
    at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
    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:715)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:707)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:702)
    at org.myschool.timeline.Timeline_App.App.main(App.java:120)
17/01/2016 02:10:41.860 [main] INFO o.h.e.j.c.i.DriverManagerConnectionProviderImpl - HHH000030: Cleaning up connection pool 
17/01/2016 02:10:41.862 [main] DEBUG o.h.b.r.i.BootstrapServiceRegistryImpl - Implicitly destroying Boot-strap registry on de-registration of all child ServiceRegistries
exception, destroyed registry

Full output: 全输出:

17/01/2016 02:10:35.891 [main] DEBUG org.jboss.logging - Logging Provider: org.jboss.logging.Slf4jLoggerProvider
17/01/2016 02:10:35.943 [main] DEBUG o.h.i.i.IntegratorServiceImpl - Adding Integrator [org.hibernate.cfg.beanvalidation.BeanValidationIntegrator].
17/01/2016 02:10:35.949 [main] DEBUG o.h.i.i.IntegratorServiceImpl - Adding Integrator [org.hibernate.secure.spi.JaccIntegrator].
17/01/2016 02:10:35.953 [main] DEBUG o.h.i.i.IntegratorServiceImpl - Adding Integrator [org.hibernate.cache.internal.CollectionCacheInvalidator].
17/01/2016 02:10:35.987 [main] DEBUG o.h.b.r.s.i.StrategySelectorImpl - Registering named strategy selector [org.hibernate.dialect.Dialect] : [MySQL5] -> [org.hibernate.dialect.MySQL5Dialect] (replacing [org.hibernate.dialect.MySQL5Dialect])
17/01/2016 02:10:35.987 [main] DEBUG o.h.b.r.s.i.StrategySelectorImpl - Registering named strategy selector [org.hibernate.dialect.Dialect] : [MySQL5InnoDB] -> [org.hibernate.dialect.MySQL5InnoDBDialect] (replacing [org.hibernate.dialect.MySQL5InnoDBDialect])
17/01/2016 02:10:36.082 [main] INFO  org.hibernate.Version - HHH000412: Hibernate Core {4.3.11.Final}
17/01/2016 02:10:36.086 [main] INFO  o.h.cfg.Environment - HHH000206: hibernate.properties not found
17/01/2016 02:10:36.089 [main] INFO  o.h.cfg.Environment - HHH000021: Bytecode provider name : javassist
17/01/2016 02:10:37.928 [main] DEBUG o.h.s.i.JaxbProcessor - cfg.xml document did not define namespaces; wrapping in custom event reader to introduce namespace information
17/01/2016 02:10:38.405 [main] DEBUG o.h.s.spi.ServiceBinding - Overriding existing service binding [org.hibernate.secure.spi.JaccService]
adds all the types
17/01/2016 02:10:38.651 [main] DEBUG o.h.i.f.i.DefaultIdentifierGeneratorFactory - Registering IdentifierGenerator strategy [uuid2] -> [org.hibernate.id.UUIDGenerator]
17/01/2016 02:10:38.652 [main] DEBUG o.h.i.f.i.DefaultIdentifierGeneratorFactory - Registering IdentifierGenerator strategy [guid] -> [org.hibernate.id.GUIDGenerator]
17/01/2016 02:10:38.654 [main] DEBUG o.h.i.f.i.DefaultIdentifierGeneratorFactory - Registering IdentifierGenerator strategy [uuid] -> [org.hibernate.id.UUIDHexGenerator]
17/01/2016 02:10:38.654 [main] DEBUG o.h.i.f.i.DefaultIdentifierGeneratorFactory - Registering IdentifierGenerator strategy [uuid.hex] -> [org.hibernate.id.UUIDHexGenerator]
17/01/2016 02:10:38.657 [main] DEBUG o.h.i.f.i.DefaultIdentifierGeneratorFactory - Registering IdentifierGenerator strategy [hilo] -> [org.hibernate.id.TableHiLoGenerator]
17/01/2016 02:10:38.658 [main] DEBUG o.h.i.f.i.DefaultIdentifierGeneratorFactory - Registering IdentifierGenerator strategy [assigned] -> [org.hibernate.id.Assigned]
17/01/2016 02:10:38.660 [main] DEBUG o.h.i.f.i.DefaultIdentifierGeneratorFactory - Registering IdentifierGenerator strategy [identity] -> [org.hibernate.id.IdentityGenerator]
17/01/2016 02:10:38.661 [main] DEBUG o.h.i.f.i.DefaultIdentifierGeneratorFactory - Registering IdentifierGenerator strategy [select] -> [org.hibernate.id.SelectGenerator]
17/01/2016 02:10:38.662 [main] DEBUG o.h.i.f.i.DefaultIdentifierGeneratorFactory - Registering IdentifierGenerator strategy [sequence] -> [org.hibernate.id.SequenceGenerator]
17/01/2016 02:10:38.663 [main] DEBUG o.h.i.f.i.DefaultIdentifierGeneratorFactory - Registering IdentifierGenerator strategy [seqhilo] -> [org.hibernate.id.SequenceHiLoGenerator]
17/01/2016 02:10:38.665 [main] DEBUG o.h.i.f.i.DefaultIdentifierGeneratorFactory - Registering IdentifierGenerator strategy [increment] -> [org.hibernate.id.IncrementGenerator]
17/01/2016 02:10:38.666 [main] DEBUG o.h.i.f.i.DefaultIdentifierGeneratorFactory - Registering IdentifierGenerator strategy [foreign] -> [org.hibernate.id.ForeignGenerator]
17/01/2016 02:10:38.667 [main] DEBUG o.h.i.f.i.DefaultIdentifierGeneratorFactory - Registering IdentifierGenerator strategy [sequence-identity] -> [org.hibernate.id.SequenceIdentityGenerator]
17/01/2016 02:10:38.668 [main] DEBUG o.h.i.f.i.DefaultIdentifierGeneratorFactory - Registering IdentifierGenerator strategy [enhanced-sequence] -> [org.hibernate.id.enhanced.SequenceStyleGenerator]
17/01/2016 02:10:38.670 [main] DEBUG o.h.i.f.i.DefaultIdentifierGeneratorFactory - Registering IdentifierGenerator strategy [enhanced-table] -> [org.hibernate.id.enhanced.TableGenerator]
17/01/2016 02:10:38.686 [main] WARN  o.h.e.j.c.i.DriverManagerConnectionProviderImpl - HHH000402: Using Hibernate built-in connection pool (not for production use!)
17/01/2016 02:10:38.700 [main] INFO  o.h.e.j.c.i.DriverManagerConnectionProviderImpl - HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://67.190.147.230:3306/school]
17/01/2016 02:10:38.701 [main] INFO  o.h.e.j.c.i.DriverManagerConnectionProviderImpl - HHH000006: Autocommit mode: false
17/01/2016 02:10:38.704 [main] INFO  o.h.e.j.c.i.DriverManagerConnectionProviderImpl - HHH000115: Hibernate connection pool size: 20 (min=1)
17/01/2016 02:10:38.705 [main] DEBUG o.h.e.j.c.i.DriverManagerConnectionProviderImpl - Initializing Connection pool with 1 Connections
17/01/2016 02:10:40.892 [main] DEBUG o.h.e.j.i.JdbcServicesImpl - JDBC version : 4.0
17/01/2016 02:10:40.897 [main] DEBUG o.h.e.j.c.i.StandardRefCursorSupport - Unexpected error trying to gauge level of JDBC REF_CURSOR support : null
17/01/2016 02:10:40.963 [main] INFO  o.h.dialect.Dialect - HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
17/01/2016 02:10:41.268 [main] DEBUG o.h.i.SessionFactoryImpl - Building session factory
17/01/2016 02:10:41.275 [main] DEBUG o.h.e.t.j.p.i.JtaPlatformInitiator - No JtaPlatform was specified, checking resolver
17/01/2016 02:10:41.276 [main] DEBUG o.h.e.t.j.p.i.JtaPlatformResolverInitiator - No JtaPlatformResolver was specified, using default [org.hibernate.engine.transaction.jta.platform.internal.StandardJtaPlatformResolver]
17/01/2016 02:10:41.282 [main] DEBUG o.h.e.t.j.p.i.StandardJtaPlatformResolver - Could not resolve JtaPlatform, using default [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
17/01/2016 02:10:41.292 [main] DEBUG o.h.cfg.SettingsFactory - Automatic flush during beforeCompletion(): disabled
17/01/2016 02:10:41.292 [main] DEBUG o.h.cfg.SettingsFactory - Automatic session close at end of transaction: disabled
17/01/2016 02:10:41.293 [main] DEBUG o.h.cfg.SettingsFactory - JDBC batch size: 15
17/01/2016 02:10:41.293 [main] DEBUG o.h.cfg.SettingsFactory - JDBC batch updates for versioned data: disabled
17/01/2016 02:10:41.293 [main] DEBUG o.h.cfg.SettingsFactory - Scrollable result sets: enabled
7/01/2016 02:10:41.293 [main] DEBUG o.h.cfg.SettingsFactory - Wrap result sets: disabled
17/01/2016 02:10:41.293 [main] DEBUG o.h.cfg.SettingsFactory - JDBC3 getGeneratedKeys(): enabled
17/01/2016 02:10:41.294 [main] DEBUG o.h.cfg.SettingsFactory - multi-tenancy strategy : NONE
17/01/2016 02:10:41.294 [main] DEBUG o.h.cfg.SettingsFactory - Connection release mode: auto
17/01/2016 02:10:41.294 [main] INFO  o.h.e.t.i.TransactionFactoryInitiator - HHH000399: Using default transaction strategy (direct JDBC transactions)
17/01/2016 02:10:41.300 [main] DEBUG o.h.cfg.SettingsFactory - Using BatchFetchStyle : LEGACY
17/01/2016 02:10:41.300 [main] DEBUG o.h.cfg.SettingsFactory - Maximum outer join fetch depth: 2
17/01/2016 02:10:41.300 [main] DEBUG o.h.cfg.SettingsFactory - Default batch fetch size: 1
17/01/2016 02:10:41.301 [main] DEBUG o.h.cfg.SettingsFactory - Generate SQL with comments: disabled
17/01/2016 02:10:41.301 [main] DEBUG o.h.cfg.SettingsFactory - Order SQL updates by primary key: disabled
17/01/2016 02:10:41.301 [main] DEBUG o.h.cfg.SettingsFactory - Order SQL inserts for batching: disabled
17/01/2016 02:10:41.301 [main] DEBUG o.h.cfg.SettingsFactory - Default null ordering: none
17/01/2016 02:10:41.302 [main] DEBUG o.h.cfg.SettingsFactory - Query translator: org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory
17/01/2016 02:10:41.306 [main] INFO  o.h.h.i.a.ASTQueryTranslatorFactory - HHH000397: Using ASTQueryTranslatorFactory
17/01/2016 02:10:41.307 [main] DEBUG o.h.cfg.SettingsFactory - Query language substitutions: {}
17/01/2016 02:10:41.307 [main] DEBUG o.h.cfg.SettingsFactory - JPA-QL strict compliance: disabled
17/01/2016 02:10:41.307 [main] DEBUG o.h.cfg.SettingsFactory - Second-level cache: enabled
17/01/2016 02:10:41.307 [main] DEBUG o.h.cfg.SettingsFactory - Query cache: disabled
17/01/2016 02:10:41.309 [main] DEBUG o.h.c.i.RegionFactoryInitiator - Cache region factory : org.hibernate.cache.internal.NoCachingRegionFactory
17/01/2016 02:10:41.314 [main] DEBUG o.h.cfg.SettingsFactory - Optimize cache for minimal puts: disabled
17/01/2016 02:10:41.314 [main] DEBUG o.h.cfg.SettingsFactory - Structured second-level cache entries: disabled
17/01/2016 02:10:41.314 [main] DEBUG o.h.cfg.SettingsFactory - Second-level cache direct-reference entries: disabled
17/01/2016 02:10:41.314 [main] DEBUG o.h.cfg.SettingsFactory - Automatic eviction of collection cache: disabled
17/01/2016 02:10:41.314 [main] DEBUG o.h.cfg.SettingsFactory - Statistics: disabled
17/01/2016 02:10:41.315 [main] DEBUG o.h.cfg.SettingsFactory - Deleted entity synthetic identifier rollback: disabled
17/01/2016 02:10:41.316 [main] DEBUG o.h.cfg.SettingsFactory - Default entity-mode: pojo
17/01/2016 02:10:41.317 [main] DEBUG o.h.cfg.SettingsFactory - Named query checking : enabled
17/01/2016 02:10:41.317 [main] DEBUG o.h.cfg.SettingsFactory - Check Nullability in Core (should be disabled when Bean Validation is on): enabled
17/01/2016 02:10:41.331 [main] DEBUG o.h.cfg.SettingsFactory - Allow initialization of lazy state outside session : : disabled
17/01/2016 02:10:41.332 [main] DEBUG o.h.cfg.SettingsFactory - JTA Track by Thread: enabled
17/01/2016 02:10:41.357 [main] DEBUG o.h.i.SessionFactoryImpl - Session factory constructed with filter configurations : {}
17/01/2016 02:10:41.384 [main] DEBUG o.h.s.spi.JaccIntegrator - Skipping JACC integration as it was not enabled
17/01/2016 02:10:41.592 [main] DEBUG o.h.i.SessionFactoryRegistry - Initializing SessionFactoryRegistry : org.hibernate.internal.SessionFactoryRegistry@36916eb0
17/01/2016 02:10:41.597 [main] DEBUG o.h.i.SessionFactoryRegistry - Registering SessionFactory: 6757530c-07f1-45bd-8c6f-a3a9697d6341 (<unnamed>)
17/01/2016 02:10:41.597 [main] DEBUG o.h.i.SessionFactoryRegistry - Not binding SessionFactory to JNDI, no JNDI name configured
17/01/2016 02:10:41.597 [main] DEBUG o.h.i.SessionFactoryImpl - Instantiated session factory
17/01/2016 02:10:41.598 [main] DEBUG o.h.i.NamedQueryRepository - Checking 0 named HQL queries
17/01/2016 02:10:41.598 [main] DEBUG o.h.i.NamedQueryRepository - Checking 0 named SQL queries
17/01/2016 02:10:41.610 [main] DEBUG o.h.s.i.StatisticsInitiator - Statistics initialized [enabled=false]
sessionfactory made, now creating session
made session
17/01/2016 02:10:41.739 [main] DEBUG o.h.e.t.s.AbstractTransactionImpl - begin
17/01/2016 02:10:41.740 [main] DEBUG o.h.e.j.i.LogicalConnectionImpl - Obtaining JDBC connection
17/01/2016 02:10:41.740 [main] DEBUG o.h.e.j.i.LogicalConnectionImpl - Obtained JDBC connection
17/01/2016 02:10:41.740 [main] DEBUG o.h.e.t.i.j.JdbcTransaction - initial autocommit status: false

What do I need to do to fix this and be able to save objects to the database? 我需要做些什么来解决此问题并能够将对象保存到数据库?

Fixed, I had to make the sessionfactory a different way, like this 固定,我不得不将sessionfactory设置为其他方式,例如

private static SessionFactory buildSessionFactory() {
    try{
        Configuration configuration = new Configuration();
        configuration.configure("hibernate.cfg.xml");
        StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
        SessionFactory sess = configuration.buildSessionFactory(ssrb.build());
        return sess;
    } catch (Throwable ex) {
        System.err.println("SessionFactory creation failed." + ex);
        ex.printStackTrace();
        throw new ExceptionInInitializerError(ex);
    }
}

I'm not entirely sure why this worked but im guessing it wasn't reading the hibernate.cfg.xml the other way 我不完全确定为什么这样做有效,但我猜它不是以其他方式读取hibernate.cfg.xml

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM