2017-05-14 41 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你正在使用註記映射,所以你不應該。 –

相關問題