19

I've got a really simple class:

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 = "users")
public class User {

    @Column(name = "firstName")
    private String firstName;

    @Column(name = "lastName")
    private String lastName;

    @Column(name = "email")
    private String email;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name = "id")
    private long 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 getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
}

I call it using this main:

public class Main {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        HibernateUtil.buildSessionFactory();
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        User u = new User();
        u.setEmail("[email protected]");
        u.setFirstName("David");
        u.setLastName("Gray");

        session.save(u);
        session.getTransaction().commit();
        System.out.println("Record committed");
        session.close();


    }

}

I keep getting this MappingException:

Exception in thread "main" org.hibernate.MappingException: Unknown entity: org.assessme.com.entity.User
    at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:1172)
    at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1316)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:117)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:204)
    at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:189)
    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:670)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:662)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:658)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:352)
    at $Proxy4.save(Unknown Source)
    at Main.main(Main.java:20)

My HibernateUtil is:

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtil {

    private static SessionFactory sessionFactory;
    private static ServiceRegistry serviceRegistry;

    public static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            Configuration configuration = new Configuration();
            configuration.configure();
            serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();     
            return new Configuration().configure().buildSessionFactory(serviceRegistry);
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

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

}

Does anyone have any ideas as I've looked at so many duplicates but the resolutions don't appear to work for me. This is my hibernate.cfg.xml:

<?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/ssme</property>
        <property name="connection.username">root</property>
        <property name="connection.password">mypassword</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>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</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 and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">update</property>

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

7 Answers 7

21

You should use AnnotationConfiguration instead of Configuration and then call

configuration.addAnnotatedClass(User.class);

to add your class to the list of mapped classes.

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

2 Comments

Ah, should I do this in my hibernateutil, is it best practice to do that all in one class would you say?
Depends on the size of your project. If you have only a couple of mapped classes you can do this in your HibernateUtil. For bigger projects you can e.g. use reflection to add all classes of a specific package to hibernate, or you can use a mapping config file.
14

Add to hibernate.cfg.xml before </session-factory> this:

<mapping class="org.assessme.com.entity.User" />

Comments

4

Consider using AnnotationConfiguration described here.

You could either use its addClass(User.class) method, or if you're persisting multiple entities use the addPackage("org.assessme.com.entity") method.

You're kind of reinventing the wheel with this HibernateUtil class. Consider using Spring so you can leverage something like its AnnotationSessionFactoryBean.

Comments

2

I forgot to add the hbm.xml mapping into my cfg.xml file. As soon as I added it, this exception disappeared.

<mapping resource="com/mycompany/backend/hibernate/CServiceCenters.hbm.xml" />

Comments

2

Do you have any persistence.xml or hibernate.cfg.xml? If you have to add your mapping class in it so hibernate get understand your class is mapping to the database. If you have hibernate.cfg.xml you can add like this

<mapping class="com.entity.Users"/>

Comments

1

Add below line to your hibernate.cfg.xml

<mapping class="fully qualified Entity class name"/>

Comments

0

I also faced a similar issue but it got resolved when I appended the MySQL version in the dialect. org.hibernate.dialect.MySQL8Dialect

Compatibility issue it seems.

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.