1

I'm using Hibernate 5.0.7 and I've a problem with annotation configuration.

This is my hibernate.cfg.xml file:

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.org/dtd/hibernate-configuration-3.0.dtd"> 
<hibernate-configuration>
<session-factory>

    <property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
    <property name="hibernate.connection.url">jdbc:sqlserver://localhost:1433;DatabaseName=mydb</property>
    <property name="hibernate.connection.username">sa</property>
    <property name="hibernate.connection.password">sa</property>

    <property name="hibernate.current_session_context_class">thread</property>
    <property name="hibernate.show_sql">true</property>

    <mapping class="com.domain.Person"/>

</session-factory>

I configure the session factory in this way:

    Configuration configuration = new Configuration();
    configuration.configure("hibernate.cfg.xml");

    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();

    SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);

    return sessionFactory;

When I try to execute a query on Person class I obtained an empty list. I discovered that the class Person is not loaded properly in the session factory (sessionFactory.getAllClassMetadata() returns empty list) and the only way to do that is to add manually the class:

 configuration.addAnnotatedClass(Person.class);

How can I solve?

xc93hil
  • 105
  • 1
  • 9

1 Answers1

4

Your session factory configuration is incorrect for Hibernate 5. When you do configuration.buildSessionFactory(serviceRegistry), Configuration lost all information about mapping that gets by call configuration.configure("hibernate.cfg.xml").

If you use Hibernate 5, you can create a session factory by this way

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

You don't need to pass hibernate.cfg.xml to the configure() method because of this name is used by default, so configure("hibernate.cfg.xml") is the same as configure().

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