2017-05-14 58 views
1

我想构建一个小型控制台应用程序,只需学习Hibernate目的就可以执行测试。不幸的是,hibernate返回时没有数据,当一个列表应该由实体填充时,它抛出outofindex异常。我认为由于没有结果回来。我一直在阅读这里的教程和问题,但我无法找到发生这种情况的原因。为什么hibernate从数据库返回没有实体,但是给定的表有数据?

JDBC连接运行良好,它从DataGrip复制。

还有哪些其他详细的应该检查更多?对不起,我在这个世界完全没有经验。

请找到下面的代码。

<?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> 

来源:

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; 
    } 
} 

类取东西:

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 
@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) 
); 

日志:

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 : [email protected] 
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 

回答

1

您需要在SessionFactory注册的entites。 您可以通过这种方式编辑hibernate.cfg.xml做到这一点:

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

您可以使用Spring扫描包添加entites的,也是如此。或者,出于测试目的,EntityScannerhere

Appart说,删除所有与EntityManager相关的行并使用Session。删除它:

EntityManager em = sessionFactory.createEntityManager(); 
+0

我添加了映射到hibernate.cfg.xml,它的工作原理。为什么你建议我应该使用Session而不是EntityManager? AFAIK Session是hibernate,EntityManager是JPA。哪个更好,为什么?我读了一些使用JPA接口的地方更可取。我相信由于它是一般的。 – SayusiAndo

+0

@SayusiAndo我不知道,什么是可取的。但是你使用'SessionFactory'和'Session'。如果你想使用JPA,你应该使用'PersistentContext'和'EntityManager'。 –

+0

啊,我明白了!感谢您的澄清!我不应该混淆两者。 – SayusiAndo

1

Hibernate SessionFactory不知道你的实体。您需要将以下资源添加到标记内的hibernate.cfg.xml文件中,以替换具有正确名称的hbm.xml文件的实体。

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

我想我不需要添加包含映射信息的xml文件,如果它们通过注释添加到实体类中的话。或者仅在EJB3的情况下才是真的? – SayusiAndo

+0

@SayusiAndo你正在使用注记映射,所以你不应该。 –

相关问题