0

While learning Hibernate and associated design patterns (https://examples.javacodegeeks.com/enterprise-java/hibernate/hibernate-jpa-dao-example/) I am facing an issue with org.hibernate.MappingException: Unknown entity: com.mycompany.mavenproject1.entity.Book.

Using latest Hibernate with an embedded HSQLDB for study purposes.

Using annotated entity file

@Entity
@Table(name = "book")
public class Book {
@Id
@Column(name = "id")
private String id;
...  

bookDAO

private static SessionFactory getSessionFactory() {

    try {
        // Build a SessionFactory object from session-factory config
        // defined in the hibernate.cfg.xml file.
        Configuration configuration = new Configuration().configure();
        StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties());
        SessionFactory sessionFactory = configuration.buildSessionFactory(builder.build());
        return sessionFactory;
    } catch (Throwable e) {
        System.err.println("Error in creating SessionFactory object."
                + e.getMessage());
        throw new ExceptionInInitializerError(e);
    }
}

public void persist(Book entity) {
    getCurrentSession().save(entity);
}

BookService

public void persist(Book entity) {
    bookDao.openCurrentSessionwithTransaction();
    bookDao.persist(entity);
    bookDao.closeCurrentSessionwithTransaction();
}

App

BookService bookService = new BookService();
Book book1 = new Book("1", "The Brothers Karamazov", "Fyodor Dostoevsky");
bookService.persist(book1);

hibernate.cfg.xml

<property name="hibernate.current_session_context_class">thread</property>
<mapping package="com.mycompany.mavenproject1.entity"/>

I am not able to figure out why that exception is thrown. Many thanks.

Marko
  • 47
  • 5

2 Answers2

0

As it's noted here:

The <mapping package="..."/> entry is for configuring meta-data defined on the package itself, not for classes in that package.

So, you should use some solutions proposed in the mentioned question or expliсitly provide a list of all entities in the hibernate.cfg.xml:

<mapping class="com.mycompany.mavenproject1.entity.Book"/>
<!--  other entities  -->
SternK
  • 11,649
  • 22
  • 32
  • 46
0

found a hint since Hibernate 5.x there have been changes implemented.

with this code the tutorial is working fine.

StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
                .configure()
                .build();

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

        return metadata.getSessionFactoryBuilder().build();
Marko
  • 47
  • 5