1

Going through the "Introduction to Hibernate" tutorials on PluralSight. I have this exception error. The full error being:

Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.simpleprogrammer.User
    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 com.simpleprogrammer.Program.main(Program.java:15)

Not sure what is wrong. I created the User.java pojo. I created a the table that matched the pojo. I created the mapping and then added the mapping to the hibernate.cfg.xml file. However, still getting the error. Can anyone help me through this?

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 name="">
  <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="hibernate.connection.url">jdbc:mysql://localhost:3306</property>
  <property name="hibernate.connection.username">root</property>
  <property name="hibernate.default_schema">protein_tracker</property>
  <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
  <mapping class="com.simpleprogrammer.User" resource="com/simpleprogrammer/User.hbm.xml"/>
 </session-factory>
</hibernate-configuration>

Program.java

public class Program {
    public static void main(String[] args) {
        System.out.println("Hello World!");
        Session session = HibernateUtilities.getSessionFactory().openSession();
        session.beginTransaction();

        User user = new User();
        user.setName("Joe");
        user.setGoal(250);
        session.save(user);

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

User.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 Oct 17, 2015 11:44:47 AM by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
    <class name="com.simpleprogrammer.User" table="USERS">
        <id name="id" type="int">
            <column name="ID" />
            <generator class="identity" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="NAME" />
        </property>
        <property name="total" type="int">
            <column name="TOTAL" />
        </property>
        <property name="goal" type="int">
            <column name="GOAL" />
        </property>
    </class>
</hibernate-mapping>

User.java

package com.simpleprogrammer;

public class User {
    private int id;
    private String name;
    private int total;
    private int goal;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getTotal() {
        return total;
    }
    public void setTotal(int total) {
        this.total = total;
    }
    public int getGoal() {
        return goal;
    }
    public void setGoal(int goal) {
        this.goal = goal;
    }
}

HibernateUtilities.java

package com.simpleprogrammer;

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

public class HibernateUtilities {

    private static SessionFactory sessionFactory;
    private static ServiceRegistry serviceRegistry;

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

            serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        }
        catch(HibernateException exception) {
            System.out.println("Problem creating session factory!");
        }   
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}
9
  • do you've the mapping XML at that location? also just add <mapping resource="com/simpleprogrammer/User.hbm.xml"/> in cfg file Commented Oct 18, 2015 at 4:58
  • Yes I am sure that the XML is at that location. I have also added a mapping tag just for the resource Commented Oct 18, 2015 at 5:03
  • I don't have the setup :( could you try with forwarding slash in the path ex /com/simpleprogrammer/User.hbm.xml Commented Oct 18, 2015 at 5:20
  • 1
    If the tutorial still teaches XML-based mapping instead of annotations, it's completely obsolete. Find another tutorial. Commented Oct 18, 2015 at 6:54
  • 1
    My work is using XML-based mapping, so this is not possible Commented Oct 18, 2015 at 14:59

12 Answers 12

16

LinhSaysHi, I've executed your code with Hibernate 5 and I have the exact same error. I've executed it with Hibernate 4 and there is no problem.

The tutorial on Pluralsight has been created for Hibernate 4. Here is a session factory builder that works with Hibernate 5:

public class HibernateUtilities_5 {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    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();

        } catch (HibernateException he) {
            System.out.println("Session Factory creation failure");
            throw he;
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Coli your solution worked like a charm.But how can I check the same?I mean how can I downgrade my hibernate version to 4 and check like you.If I know this process I can solve my bugs due to versioning issues in future.Thanks in advance..
Well if you use Maven you can just specify the version you want in the pom.xml.
7

I also faced the same error while trying it out with Hibernate 5.1.1. But I resolved it by replacing ServiceRegistry interface with StandardServiceRegistryBuilder and used "metadatasources" to create session factory. Please see my code below

static
{
    try
    {
        //Configuration configuration = new Configuration().configure();
        standardServiceRegistry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml")
                                    .build();
        Metadata metadata = new MetadataSources(standardServiceRegistry)
                                .getMetadataBuilder().build();
        sessionFactory = metadata.getSessionFactoryBuilder().build();

    }catch(HibernateException exception)
    {
        System.out.println("problem creating session factory!");
    }
}

public static SessionFactory getSessionFactory(){

    return sessionFactory;
}

I made these changes and it worked like a charm. please make changes in your code to the way you load the configuration file and try it again. Let me know if you still face hurdles.

Comments

2

Please check the schema name that you created in MySQL and the one specied in hibernate.cfg file.It was mismatching for me and i was getting same issue.

Also modify connection url like below and remove the default schema field from hibernate.cfg. jdbc:mysql://localhost:3306/protein_tracker

this worked for me.

Comments

2

Change the code as per Hibernate 5

    static
    {
        try {
            //Configuration configuration = new Configuration().configure();
            serviceRegistry = new 
            StandardServiceRegistryBuilder().configure("hibernate.cfg.xml")
                                        .build();
            Metadata metadata = new MetadataSources(serviceRegistry)
                                .getMetadataBuilder().build();
            sessionFactory = metadata.getSessionFactoryBuilder().build();   
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
    public static SessionFactory getSessionFactory() {
    return sessionFactory;
    }

give the give full class path in user.hbm.xml

     <class name="com.simpleprogrammer.Users" table="USERS">

map the resource in hibernate.cfg.xml

      <mapping resource="com/simpleprogrammer/Users.hbm.xml"/>

and execute the following code

    Session session = HibernateUtilities.getSessionFactory().openSession();

    session.beginTransaction();

    Users user = new Users();

    user.setuserName("Prince");
    user.setGoal(100);
    user.setId(101);
    user.setTotal(10);

    session.save(user);

    session.getTransaction().commit(); 
    session.close();
    HibernateUtilities.getSessionFactory().close();

Comments

1

The mapping is having a little issue. Make sure the path you specified is correct. When i had same issue, i only re-modified my mapping in the hibernate.cfg.xml to

<mapping class="com.simpleprogrammer.User"/>

Other attribute like resource were not added

Comments

0

I used your example and was able to get it to work with a few minor tweaks.

Verified that User.hbm.xml was located in src/main/resources/com/simpleprogrammer. Changed to lowercase table="users"

Then in hibernate.cfg.xml:

  1. removed the name="" attribute from session-factory.
  2. added a <property name="hibernate.connection.password">SomePassword</property>
  3. added <property name="hibernate.hbm2ddl.auto">create</property>

Comments

0

there is problem with Hibernate jars... here i can see u are using the Hibernate 4....for developing the project... so add the hibernate 4.3.5 jar it should work.........

if u are not working with metadata than better to use hibernate 4.3 jar

Comments

0

The easy solution is, when you create SessionFactory object, just check your HibernateUtil class which you have created. Write correct hibernateUtility class and import correct package. If you have created multiple src packages in single project then keep packages name for hibernateutility class different.

Comments

0

Try this method for this problem:

  1. In Entity Class use the annotations like this Annotations
  2. Make Sure That FactoryConfiguration class is like this FactoryConfiguration Class

1 Comment

Please don't post code images or bugs if possible, copy your code or code error into answer with block code format. Please take the tour and read How to Answer: stackoverflow.com/help/how-to-answer
0

for this issue the simple solution is to make sure that, you need to update correctly in cfg.xml file 1.mapping should be done correctly as package.className. 2.Make sure you make th pojo class as @Entity

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
0

I faced the same problem what fixed my problem is I used method .addAnnotatedClass("ClassName".class) Example:

SessionFactory factory = new Configuration()
    .configure()
    .addAnnotatedClass(Students.class)
    .buildSessionFactory();

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
0

Use

Configuration.addAnnotatedClass(com.simpleprogrammer.User); 

2 Comments

Please, edit and try for How to Answer, describe the effect of what you propose and explain why it helps to solve the problem, make the additional insight more obvious which you contribute beyond existing answers. Find help with formatting your post here: stackoverflow.com/help/formatting . Consider taking the tour. Have fun.
Please format every code chunk. Shortcut is Ctrl+K

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.