2

The following code works just fine with Hibernate 4.3, but when I try the same code using Hibernate 5.0 it results in the following error:

Exception in thread "main" org.hibernate.MappingException: Unknown entity: entity.Message
    at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:776)
    at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1451)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:100)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
    at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
    at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
    at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:678)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:670)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:665)
    at client.Main.main(Main.java:14)

Could somebody help me understand why is it happening?


Following is the code being used to test the example:

Main.java

package client;
import org.hibernate.Session;
import util.HibernateUtil;
import entity.Message;

public class Main {
    public static void main(String[] args) {        
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();

        Message message = new Message( "Hello Hibernate 5" );

        session.save(message);    

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

HibernateUtil.java

package util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {    
    private static final SessionFactory sessionFactory = buildSessionFactory();    
    private static SessionFactory buildSessionFactory() {
        try {           
            Configuration configuration = new Configuration().configure("hibernate.cfg.xml");     
            return configuration.buildSessionFactory( new StandardServiceRegistryBuilder().applySettings( configuration.getProperties() ).build() );
        }
        catch (Throwable ex) {                
            throw new ExceptionInInitializerError(ex);
        }
    }

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

Message.java

package entity;

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="message")
public class Message {

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

    @Column(name="TEXT")    
    private String text;

    public Message() {}
    public Message(String text) {
        this.text = text;
    }   
}

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="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/hello</property>
        <property name="connection.username">root</property>
        <property name="connection.password">pass</property>

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

        <mapping class="entity.Message"/>

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

SQL Database Schema (RDBMS: MYSQL)

CREATE DATABASE `hello`;
USE `hello`;
CREATE TABLE `message` (
`ID` BIGINT(20) NOT NULL AUTO_INCREMENT,
`TEXT` VARCHAR(255) NULL DEFAULT NULL,
PRIMARY KEY (`ID`)
);
3
  • what is your directory structure Commented Oct 8, 2015 at 2:01
  • @JunedAhsan: Its a Java Project in Eclipse IDE with src being the source folder in the classpath. hibernate.cfg.xml is right under the src folder. Main.java is in the client package, HibernateUtil.java in util package and Message.java in the entity package. Commented Oct 8, 2015 at 2:06
  • I think its because you didnt set up a default schema property in your hibernate-cfg.xml. Let me take a look, and I'll be right back with the answer Commented Oct 14, 2015 at 20:01

2 Answers 2

11

UPDATED: In Hibernate 5.0.x, configuration with standard service registry is deprecated

Instead you should bootstrap it with Metadata:

In your HibernateUtil class, you should add

   private static SessionFactory buildSessionFactory() {
    try {           
        StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
        .configure( "hibernate.cfg.xml" )
        .build();

        Metadata metadata = new MetadataSources( standardRegistry )
        .getMetadataBuilder()
        .build();

        return metadata.getSessionFactoryBuilder().build();

    }

And as a side note, change the ID declaration of your Message Class to

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="ID")  
private Long id;

So hibernate can properly use mySql's auto increment, otherwise it will throw an exception.

Sign up to request clarification or add additional context in comments.

12 Comments

It doesn't make any difference. I am stilling getting the same error.
ok, im setting up a new project in order to debug it, are you using maven?
not to sound like an ass, but I recreated your project in eclipse and it worked perfectly. I shared it on github: github.com/bruno-cw/pizzadepot/tree/master/Hibernate if you could share yours, it would be a great help to identify whats wrong. I ruled out any problem with db,
No, am not using Maven. Just a Java project in eclipse with jar files in the c.asspath
Thanks for the project @javaguest, let me try it.
|
0

Alternatively, you could do the following in Hibernate 5+ and have your SessionFactory/Session creating class extend the HibernateHelper class below:

package com.company.hibernatehelper;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateHelper {
    private static SessionFactory sessionFactory = null;

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.