1

I'm using Hibernate 5.0.6 and Hibernate annotations 3.5.6-Final with MySql 5.1.37 in a standalone maven java application.

I'm trying to make a simply persistence example work but I receive the following error when I call save:

0    [main] ERROR edu.uci.ics.crawler4j.crawler.CrawlController  - Error    happened
org.hibernate.MappingException: Unknown entity: br.com.alexpfx.supermarket.crawler.model.domain.Product

The classes Is pointed via mapping class in the configuration file. But it is unable to find.

        <mapping class="br.com.alexpfx.supermarket.crawler.model.domain.Product" />

But when I do this in HibernateUtil:

        configure.addAnnotatedClass(Product.class);
        configure.addAnnotatedClass(Manufacturer.class);

It works. But I want to point mapping the classes in xml files.

I found several errors related to this but found no solution solved my problem. I think I'm doing something wrong.

The full stacktrace of error:

0    [main] ERROR edu.uci.ics.crawler4j.crawler.CrawlController  - Error happened
org.hibernate.MappingException: Unknown entity: br.com.alexpfx.supermarket.crawler.model.domain.Product
    at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:781)
    at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1520)
    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:679)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:671)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:666)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:338)
    at com.sun.proxy.$Proxy19.save(Unknown Source)
    at br.com.alexpfx.supermarket.crawler.crawler.mercadoribeirao.MercadoRibeiraoCrawler.init(MercadoRibeiraoCrawler.java:47)
    at br.com.alexpfx.supermarket.crawler.crawler.Crawler.<init>(Crawler.java:16)
    at br.com.alexpfx.supermarket.crawler.crawler.mercadoribeirao.MercadoRibeiraoCrawler.<init>(MercadoRibeiraoCrawler.java:26)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
    at java.lang.Class.newInstance(Class.java:442)
    at edu.uci.ics.crawler4j.crawler.CrawlController.start(CrawlController.java:158)
    at edu.uci.ics.crawler4j.crawler.CrawlController.start(CrawlController.java:133)
    at br.com.alexpfx.supermarket.crawler.crawler.CrawlerStarter.start(CrawlerStarter.java:41)
    at br.com.alexpfx.supermarket.crawler.Main.save(Main.java:29)
    at br.com.alexpfx.supermarket.crawler.Main.main(Main.java:14)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

The config file is locate at: project\src\main\resources\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>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/smket</property>
        <property name="connection.username">alex</property>
        <property name="connection.password">123alex</property>
        <property name="connection.pool_size">5</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <property name="show_sql">true</property>
        <property name="hibernate.current_session_context_class">thread</property>
        <mapping class="br.com.alexpfx.supermarket.crawler.model.domain.Product" />
       <mapping class="br.com.alexpfx.supermarket.crawler.model.domain.Manufacturer" />
    </session-factory>

</hibernate-configuration>

HibernateUtil:

public class HibernateUtil {
    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            Configuration configure = new Configuration().configure("hibernate.cfg.xml");

            /*
            configure.addAnnotatedClass(Product.class);
            configure.addAnnotatedClass(Manufacturer.class);
            */

            ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configure.getProperties()).build();
            return configure.buildSessionFactory(serviceRegistry);
        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void shutdown() {
        getSessionFactory().close();
    }

}

The POJO class:

package br.com.alexpfx.supermarket.crawler.model.domain;

import javax.persistence.*;

@Entity
@Table(name = "tb_produtos")
public class Product implements BaseEntity {


    public Product() {
    }

    Product(Integer id, Manufacturer manufacturer, String description, String url, Keywords keywords) {
        this.id = id;
        this.manufacturer = manufacturer;
        this.description = description;
        this.url = url;
        this.keywords = keywords;
    }

    @Id
    @GeneratedValue
    private Integer id;

    @ManyToOne
    @JoinColumn(name = "ID_FABRICANTE")
    private Manufacturer manufacturer;

    @Column(name = "DESCRICAO")
    private String description;

    @Column(name = "URL")
    private String url;

    @Transient
    private Keywords keywords;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Manufacturer getManufacturer() {
        return manufacturer;
    }

    public void setManufacturer(Manufacturer manufacturer) {
        this.manufacturer = manufacturer;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public Keywords getKeywords() {
        return keywords;
    }

    public void setKeywords(Keywords keywords) {
        this.keywords = keywords;
    }
}
Roman C
  • 49,761
  • 33
  • 66
  • 176
alexpfx
  • 6,412
  • 12
  • 52
  • 88

2 Answers2

2

It is already a familiar problem with Hibernate 5 configuration building. You can't use Hibernate 4 configuration approach to configure Hibernate 5. So just use this

private static SessionFactory buildSessionFactory() {
        try {
             return new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
}

You can refer this for additional notes. I have implemented a configuration builder that works fine with Hibernate 4 and Hibernate 5, you can take a look on it too ConfigurationBuilder.

Community
  • 1
  • 1
v.ladynev
  • 19,275
  • 8
  • 46
  • 67
1

You didn't specify location of the hibernate configuration file hibernate.cfg.xml.

The hibernate.cfg.xml file is where all configuration needed for the interaction with the database is set. So, the database is defined there, as well as the database user credentials. The dialect is set to MySQL, and the driver is the com.mysql.jdbc.Driver. There is also a mapping attribute, where the entity class is defined. You can also set specific database options there, such as whether the schema will be created or just updated, every time the sessionFactory is created. This is configured in the hibernate.hbm2ddl.auto property, which is set to update. So the schema is only updated. If this property is set to create, then every time we run your application, the schema will be re-created, thus deleting previous data. Another property set here is the show_sql, which specifies whether the sql queries will be shown in the console or the logger. First of all, the getSessionFactory() is a method that provides a SessionFactory, the creator of Sessions, the basic interfaces between a Java application and Hibernate. The SessionFactory is built with the StandardServiceRegistryBuilder, making use of Configuration. The Configuration is where you can specify properties and mapping documents to be used when creating a SessionFactory. So, every method that interacts with the database gets a Session, making use of the getSessionFactory(), and the using the openSession() API method of SessionFactory.

public static SessionFactory getSessionFactory() {

        Configuration configuration = new Configuration().configure();

        StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties());
        SessionFactory sessionFactory = configuration
                .buildSessionFactory(builder.build());

        return sessionFactory;

    } 
Roman C
  • 49,761
  • 33
  • 66
  • 176
  • The program is reading the configuration file, because when I do: configure.addAnnotatedClass it works. even so, if he could not read the configuration file, it will stop when it call .configure() from new Configuration(), but the getSessionFactory method is called correctly. – alexpfx Dec 26 '15 at 20:00
  • I am really sorry man, but your approach works fine only for Hibernate 4 and less. For Hibernate 5 it is incorrect. Please, see my answer for additional notes. – v.ladynev Dec 26 '15 at 21:33