AndrasCsanyi
AndrasCsanyi

Reputation: 4255

Why hibernate returns no entity from db, however given table has data?

I would like to build a small console application executed by tests just of learning Hibernate purposes. Unfortunately, hibernate returns with no data and when a list should be populated by the entities it throws outofindex exception. I assume due to no result coming back. I have been reading the tutorials and questions here, but I cannot find why this happens.

JDBC connection is working well, it is copied from DataGrip.

What other detailed should be checked more? Sorry, I'm totally inexperienced in this world.

Please find the code below.

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQL95Dialect</property>
        <property name="connection.url" >jdbc:postgresql://localhost:5432/digitallibraryreports</property>
        <property name="connection.driver_class">org.postgresql.Driver</property>
        <property name="connection.username">postgres</property>
        <property name="connection.password">postgres</property>

        <property name="connection.pool_size">1</property>
        <property name="show_sql">true</property>
        <property name="format_sql">true</property>
        <property name="use_sql_comments">true</property>
        <!-- DB schema will be updated if needed -->
        <!-- <property name="hbm2ddl.auto">update</property> -->
    </session-factory>
</hibernate-configuration>

Source:

public class ETL {

    private static SessionFactory factory;

    public ETL(){
        try{
            factory = new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex){
            System.err.println("Failed to create sessionfactory" + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public SessionFactory getSessionFactory() {
        return factory;
    }
}

Class fetching stuff:

public class FeatureFetcher {

    private static SessionFactory sessionFactory;

    public FeatureFetcher() {
        ETL etl = new ETL();
        sessionFactory = etl.getSessionFactory();
    }

    public void fetchFeatures() {

        Session session = sessionFactory.openSession();
        EntityManager em = sessionFactory.createEntityManager();

        try {
            em.getTransaction().begin();
            List<Test> testEntityList = em.createQuery("FROM Test", Test.class).getResultList();

            if (testEntityList.size() > 0) {
                for (Iterator<Test> iterator = testEntityList.iterator(); iterator.hasNext(); ) {
                    Test testEntity = (Test) iterator.next();

                    System.out.println("Test Entity name: " + testEntity.getName());
                    System.out.println("Test Entity id: " + testEntity.getId());
                }

                em.getTransaction().commit();
                em.close();
            }

        } catch (HibernateException e) {
            em.getTransaction().rollback();
            e.printStackTrace();
        } finally {
            em.close();
        }

    }
}

Entity:

@Entity
@Table(name = "test", schema = "public")
public class Test {

    @javax.persistence.Id
    @GeneratedValue
    @Column(name = "id")
    public Integer Id;

    @Column(name = "name")
    public String Name;

    public Integer getId() {
        return Id;
    }

    public void setId(Integer id) {
        Id = id;
    }

    public String getName() {
        return Name;
    }

    public void setName(String name) {
        Name = name;
    }
}

SQL:

CREATE TABLE public.TEST
(
    Id INT PRIMARY KEY,
    Name VARCHAR(255)
);

Logs:

May 14, 2017 9:20:30 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.10.Final}
May 14, 2017 9:20:30 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
May 14, 2017 9:20:31 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
May 14, 2017 9:20:31 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
May 14, 2017 9:20:31 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [org.postgresql.Driver] at URL [jdbc:postgresql://localhost:5432/digitallibraryreports]
May 14, 2017 9:20:31 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=postgres, password=****}
May 14, 2017 9:20:31 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
May 14, 2017 9:20:31 PM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
May 14, 2017 9:20:31 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.PostgreSQL95Dialect
May 14, 2017 9:20:31 PM org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl useContextualLobCreation
INFO: HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
May 14, 2017 9:20:31 PM org.hibernate.type.BasicTypeRegistry register
INFO: HHH000270: Type registration [java.util.UUID] overrides previous : org.hibernate.type.UUIDBinaryType@6253c26
May 14, 2017 9:20:31 PM org.hibernate.hql.internal.QuerySplitter concreteQueries
WARN: HHH000183: no persistent classes found for query class: FROM Test
May 14, 2017 9:20:31 PM org.hibernate.hql.internal.QueryTranslatorFactoryInitiator initiateService
INFO: HHH000397: Using ASTQueryTranslatorFactory

Upvotes: 1

Views: 398

Answers (2)

v.ladynev
v.ladynev

Reputation: 19956

You need to register entites in the SessionFactory. You can do it by editing hibernate.cfg.xml by this way:

<session-factory>
  ...
  <mapping class="some.pack.Test" />
  ...
</session-factory>

You can use Spring to scan a package to add entites, as well. Or, for testing purposes, EntityScanner from here.

Appart that, remove all lines related to the EntityManager and use Session. Remove this:

EntityManager em = sessionFactory.createEntityManager();

Upvotes: 1

rslj
rslj

Reputation: 380

Hibernate SessionFactory is not aware of the your entity. You need to add the following resource to the hibernate.cfg.xml file inside the tag replacing the Entity with the correct name of the hbm.xml file.

<session-factory>
.
.
.
<mapping resource="Entity.hbm.xml"/> 
</session-factory>

Upvotes: 1

Related Questions