2014-01-06 22 views
5

我正在使用Postgres 9.2,hibernate 4.3.0 final。運行一個簡單的Hibernate項目沒有效果

我有testClass

@Entity 
@Table(name="testClass") 

public class testClass implements Serializable { 

    @Id 
    @Column(name = "id") 
    private Integer id; 

    @Column(name="name") 
    private String name; 

    public Integer getId() { 
     return id; 
    } 
} 

從另一個類的方法創建:

try { 
    new Configuration().configure("/hibernate.cfg.xml"); 
    new testClass(); 
} catch(Exception e) { 
    System.out.println(e); 
} 

這裏是我的hibernate.xml.cfg:

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" 
     "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> 
<hibernate-configuration> 
    <session-factory name="postgres"> 
     <property name="hibernate.connection.driver_class">org.postgresql.Driver</property> 
     <property name="hibernate.connection.password">123</property> 
     <property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/postgres</property> 
     <property name="hibernate.connection.username">postgres</property> 
     <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property> 
     <property name="hbm2ddl.auto">create</property> 
     <mapping class="testClass"/> 

    </session-factory> 
</hibernate-configuration> 

它執行的JBoss服務器端:

[2014-01-06 05:59:01,592] Artifact server:ejb: Artifact is deployed successfully 
17:59:22,880 INFO [org.hibernate.cfg.Configuration] configuring from resource: /hibernate.cfg.xml 
17:59:22,881 INFO [org.hibernate.cfg.Configuration] Configuration resource: /hibernate.cfg.xml 
17:59:22,889 INFO [org.hibernate.cfg.Configuration] Configured SessionFactory: postgres 

但沒有任何反應:(
我正在檢查我的PostgresDB中的新表,但沒有任何東西。

我錯過了什麼?

+0

我認爲你什麼都不做;只是打開它並閱讀它 –

+1

感謝您提供所有正確的細節,從一開始就有一個很好的問題。如果可以的話,我會+10。 –

回答

6

你預計會發生什麼?

您創建一個新的空實體,然後退出。

您不需要persist()具有實體管理器的實體(或Hibernate條款,save()Session)。因此,就數據庫而言它絕不存在。它只是一個普通的Java對象,與其他引用相同,並在最後一次引用它時被刪除。

您需要:

  • 使用Configuation產生SessionFactory和存儲SessionFactory地方訪問。你不想一直創建它,它應該在啓動時創建。容器管理的持久性和注入在這裏可以很方便。

  • 獲取從SessionFactory

  • 一個Session通過新的對象Session.save(...),所以正確的密鑰生成後得到INSERT版在DB等

這可能是一個很好的重新閱讀Hibernate和/或JPA教程以涵蓋對象生命週期的基礎知識。 The Getting Started Guide可能是一個很好的起點,特別是the section on native Hibernate APIs

個人而言,如果我在做基本的東西,我會使用JPA API來代替。 PersistenceUnit,EntityManager等。參見Getting started with Hibernate and JPA