运行一个简单的Hibernate项目没有任何效果

Wil*_*Dev 4 java postgresql hibernate

我正在使用Postgres 9.2,hibernate 4.3.0 final.

我有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;
    }
}
Run Code Online (Sandbox Code Playgroud)

从另一个类的方法创建:

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

这是我的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>
Run Code Online (Sandbox Code Playgroud)

它在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
Run Code Online (Sandbox Code Playgroud)

但没有任何反应:(
我正在检查我的PostgresDB中的新表,但没有任何东西.

我错过了什么?

Cra*_*ger 6

你期望发生什么?

您创建一个新的空实体,然后退出.

您不是persist()具有实体管理器的实体(或者在Hibernate术语中,save()对于a Session).因此,就数据库而言,它永远不存在.它只是一个普通的Java对象,并且在删除对它的最后一个引用时会收集垃圾.

你需要:

  • 使用它Configuation来生成一个SessionFactory并存储在SessionFactory可访问的地方.您不想一直创建它,它应该在启动时创建.容器管理的持久性和注入在这里很方便.

  • Session从中获得一个SessionFactory

  • 将新对象传递给Session.save(...),INSERT在适当的密钥生成等之后将其输入到DB中.

重新阅读Hibernate和/或JPA教程以涵盖对象生命周期的基础知识可能是个好主意.入门指南可能是一个很好的起点,尤其是关于本机Hibernate API的部分.

就个人而言,如果我做基本的东西,我会使用JPA API代替.PersistenceUnit,EntityManager等见开始使用Hibernate和JPA.