1

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

2 Answers 2

1

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();
Sign up to request clarification or add additional context in comments.

3 Comments

I added the mapping to hibernate.cfg.xml and it works. Why do you suggest that I should use Session instead of EntityManager? AFAIK Session is hibernate, EntityManager is JPA. Which is preferable and why? I read somewhere that using JPA interface is more preferable. I believe due to it is general.
@SayusiAndo I don't know, what is preferable. But you are using SessionFactory and Session. If you want to use JPA, you should to use PersistentContext and EntityManager.
Ahh, I see! Thanks for the clarification! I should not mix the two.
1

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>

2 Comments

I thought I don't have to add xml file(s) containing mapping information if they are added to the entity class via annotations. Or it is true in case EJB3 only?
@SayusiAndo You are using annotation mapping, so you shouldn't.

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.