1

I have gone through most of the similar issues posted here and the solution found there was to use javax.persistence.Entity import instead of org.hibernate.annotations.Entity.

I have used the correct import but still getting org.hibernate.MappingException

I am using mysql-connector-java version 6.0.5 with hibernate-core version 5.2.6.Final and hibernate-annotations version 3.5.6-Final

Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.myApp.data.entities.User
    at org.hibernate.metamodel.internal.MetamodelImpl.entityPersister(MetamodelImpl.java:620)
    at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1627)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:104)
    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:682)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:674)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:669)
    at com.myApp.data.Application.main(Application.java:26)

The pom.xml is as follows:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.myApp</groupId>
  <artifactId>hibernate-course</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>hibernate-course</name>
  <dependencies>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.2.6.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-annotations</artifactId>
        <version>3.5.6-Final</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.22</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>6.0.5</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.22</version>
    </dependency>
  </dependencies>
</project>

The following is my main class Application.java

package com.myApp.data;

import java.util.Date;

import org.hibernate.Session;

import com.myApp.data.entities.User;


public class Application {

    public static void main(String[] args) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.getTransaction().begin();

        User user = new User();
        user.setBirthDate(new Date());
        user.setCreatedBy("Smith");
        user.setCreatedDate(new Date());
        user.setEmailAddress("[email protected]");
        user.setFirstName("David");
        user.setLastName("Copperfield");
        user.setLastUpdatedBy("david");
        user.setLastUpdatedDate(new Date());

        session.save(user);

        session.close();
    }
}

User Entity class

package com.myApp.data.entities;

import java.util.Date;

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

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

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

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

    @Column(name="BIRTH_DATE")
    private Date birthDate;

    @Column(name="EMAIL_ADDRESS")
    private String emailAddress;

    @Column(name="LAST_UPDATED_DATE")
    private Date lastUpdatedDate;

    @Column(name="LAST_UPDATED_BY")
    private String lastUpdatedBy;

    @Column(name="CREATED_DATE")
    private Date createdDate;

    @Column(name="CREATED_BY")
    private String createdBy;

    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    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 Date getBirthDate() {
        return birthDate;
    }

    public void setBirthDate(Date birthDate) {
        this.birthDate = birthDate;
    }

    public String getEmailAddress() {
        return emailAddress;
    }

    public void setEmailAddress(String emailAddress) {
        this.emailAddress = emailAddress;
    }

    public Date getLastUpdatedDate() {
        return lastUpdatedDate;
    }

    public void setLastUpdatedDate(Date lastUpdatedDate) {
        this.lastUpdatedDate = lastUpdatedDate;
    }

    public String getLastUpdatedBy() {
        return lastUpdatedBy;
    }

    public void setLastUpdatedBy(String lastUpdatedBy) {
        this.lastUpdatedBy = lastUpdatedBy;
    }

    public Date getCreatedDate() {
        return createdDate;
    }

    public void setCreatedDate(Date createdDate) {
        this.createdDate = createdDate;
    }

    public String getCreatedBy() {
        return createdBy;
    }

    public void setCreatedBy(String createdBy) {
        this.createdBy = createdBy;
    }

}

Hibernate SessionFactory Configuration class

package com.myApp.data;

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();
            configuration.configure();
            return configuration
                    .buildSessionFactory(new StandardServiceRegistryBuilder()
                            .applySettings(configuration.getProperties())
                            .build());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(
                    "There was an error building the factory");
        }
    }

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

and finally 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>

        <!-- Database connection settings -->
        <property name="connection.url">jdbc:mysql://localhost:3306/ifinances?useSSL=false</property>
        <property name="connection.username">infinite</property>
        <property name="connection.password">skills</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <mapping class="com.myApp.data.entities.User"/>

    </session-factory>

</hibernate-configuration>

I checked the same thing using hibernate.properties instead of hibernate.cfg.xml by using configuration.addAnnotatedClass(User.class); and It compiled and executed with out any exception.

10
  • I would like to take a look at this method: configuration.configure(); inside your HibernateUtil Commented Jan 18, 2017 at 18:04
  • No this is not the JPA API. Tags fixed! Commented Jan 18, 2017 at 18:11
  • @MaciejKowalski I used configuration.configure(); to set hibernate.cfg.xml as default configuration as I also have a hibernate.properties file inside my resources Commented Jan 18, 2017 at 21:40
  • @NeilStockton Sorry I didnt understand what you were trying to say. Could you please explain? And I know I am using hibernate API, if you are indeed pointing out the use of import javax.persistence.Entity; instead of org.hibernate.annotations, itz because org.hibernate.annotations is deprecated and existed before JPA 1. Commented Jan 18, 2017 at 21:51
  • 2
    Could you verify what happens if you use the no-arg buildSessionFactory()? Your mapping class declaration looks correct. Commented Jan 18, 2017 at 23:06

2 Answers 2

5

Found the solution. The above code will work fine in Hibernate 4.3.6 but problem is when working with Hibernate 5. The problem is with the following code:

    return configuration
            .buildSessionFactory(new StandardServiceRegistryBuilder()
                    .applySettings(configuration.getProperties())
                    .build());

The problem is when you pass the StandardServiceRegistryBuilder as an argument inside buildSessionFactory(). When you do this the configuration loose all mapping information that is acquired through configuration.configure(); statement.

That is why the code worked fine when using hibernate.properties file (which doesnt use configuration.configure() ) but caused an exception when using hibernate.cfg.xml.

When using hibernate.cfg.xml

When using hibernate xml configuration method, you can simply return the sessionFactory that uses a no-arg buildSessionFactory() method.

The actual code the works (using hibernate.cfg.xml)

Issue solved!

package com.myApp.data;

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

import com.myApp.data.entities.User;

public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

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

            /*return configuration
                    .buildSessionFactory(new StandardServiceRegistryBuilder()
                            .applySettings(configuration.getProperties())
                            .build());  -- does not work while using hibernate.cfg.xml, but works with hibernate.properties*/

            return configuration
                    .buildSessionFactory(); 
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(
                    "There was an error building the factory");
        }
    }

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

Thanks for all who helped!

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

2 Comments

@MattC you saved my day!
Glad that worked for you. When in doubt, I try to simplify and try different variations.
0

try using AnnotationConfiguration instead of Configuration.

Configuration configuration = new AnnotationConfiguration();

1 Comment

This results in java.lang.NoClassDefFoundError: org/hibernate/cfg/Mappings exception

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.