Hibernate不会第二次创建表并挂起

时间:2014-03-26 11:02:07

标签: hibernate hibernate-mapping

嗨,我是Hibernate的新手。我正在尝试一个示例程序,当我第二次执行代码时,hibernate不会创建表并挂起。当我点击数据库表时,数据库会挂起。

我正在使用postgresql-9.3.3-1版本和hibernate-release-4.3.4.Final。

以下是我的代码段

1.hibernate.cfg.xml

<session-factory>

    <property name="connection.driver_class">org.postgresql.Driver</property>
    <property name="connection.url">jdbc:postgresql://localhost:5432/hibernatedb</property>
    <property name="connection.username">postgres</property>
    <property name="connection.password">postgres</property>

    <!-- JDBC connection pool (use the built-in) -->
    <property name="connection.pool_size">1</property>

    <!-- SQL dialect -->
    <property name="dialect">org.hibernate.dialect.PostgreSQL9Dialect</property>

    <!-- Enable Hibernate's automatic session context management -->
    <property name="current_session_context_class">thread</property>

    <!-- Echo all executed SQL to stdout -->
    <property name="show_sql">true</property>
    <property name="hbm2ddl.auto">create</property>

    <mapping class="com.pramati.dto.UserDetails"></mapping>

</session-factory>

2.我的POJO课程。我在我的pojo类中使用注释

UserDetails.java

@Entity
@Table (name="USER_DETAILS")
public class UserDetails {

@Id
private int userId;
private String userName;
@Temporal (TemporalType.DATE)
private Date joinDate;
private String address;
private String description;

public int getUserId() {
    return userId;
}
public void setUserId(int userId) {
    this.userId = userId;
}
public String getUserName() {
    return userName;
}
public void setUserName(String userName) {
    this.userName = userName;
}
public Date getJoinDate() {
    return joinDate;
}
public void setJoinDate(Date joinDate) {
    this.joinDate = joinDate;
}
public String getAddress() {
    return address;
}
public void setAddress(String address) {
    this.address = address;
}
public String getDescription() {
    return description;
}
public void setDescription(String description) {
    this.description = description;
}

}

  1. 我的Java类主要方法
  2. 我正在创建一个UserDetails对象并从新创建的UserDetails对象中检索用户名。以下是mj java代码

    公共类HibernateTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
    
        UserDetails userDetails = new UserDetails();
        userDetails.setUserId(1);
        userDetails.setUserName("Avinash");
        userDetails.setAddress("Rajeev Nagar");
        userDetails.setJoinDate(new Date());
        userDetails.setDescription("Software Engineer");
    
        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        session.save(userDetails);
        session.getTransaction().commit();
        session.close();
    
        userDetails=null;
        session = sessionFactory.openSession();
        session.beginTransaction();
        userDetails = (UserDetails)session.get(UserDetails.class, 1);
        System.out.println("User Name Retrieved is " + userDetails.getUserName());
        session.close();
    }
    

    }

    第一次运行上面的java类时,以下是eclipse控制台中显示的输出,它创建了UserDetails对象

    Mar 26, 2014 3:49:06 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
                INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
                Mar 26, 2014 3:49:06 PM org.hibernate.Version logVersion
                INFO: HHH000412: Hibernate Core {4.3.4.Final}
                Mar 26, 2014 3:49:06 PM org.hibernate.cfg.Environment <clinit>
                INFO: HHH000206: hibernate.properties not found
                Mar 26, 2014 3:49:06 PM org.hibernate.cfg.Environment buildBytecodeProvider
                INFO: HHH000021: Bytecode provider name : javassist
                Mar 26, 2014 3:49:06 PM org.hibernate.cfg.Configuration configure
                INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
                Mar 26, 2014 3:49:06 PM org.hibernate.cfg.Configuration getConfigurationInputStream
                INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
                Mar 26, 2014 3:49:06 PM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
                WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
                Mar 26, 2014 3:49:06 PM org.hibernate.cfg.Configuration doConfigure
                INFO: HHH000041: Configured SessionFactory: null
                Mar 26, 2014 3:49:06 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
                WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
                Mar 26, 2014 3:49:06 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
                INFO: HHH000401: using driver [org.postgresql.Driver] at URL [jdbc:postgresql://localhost:5432/hibernatedb]
                Mar 26, 2014 3:49:06 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
                INFO: HHH000046: Connection properties: {user=postgres, password=****}
                Mar 26, 2014 3:49:06 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
                INFO: HHH000006: Autocommit mode: false
                Mar 26, 2014 3:49:06 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
                INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
                Mar 26, 2014 3:49:06 PM org.hibernate.dialect.Dialect <init>
                INFO: HHH000400: Using dialect: org.hibernate.dialect.PostgreSQL9Dialect
                Mar 26, 2014 3:49:06 PM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
                INFO: HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
                Mar 26, 2014 3:49:06 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
                INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
                Mar 26, 2014 3:49:06 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
                INFO: HHH000397: Using ASTQueryTranslatorFactory
                Mar 26, 2014 3:49:07 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
                INFO: HHH000227: Running hbm2ddl schema export
                Hibernate: drop table USER_DETAILS cascade
                Hibernate: create table USER_DETAILS (userId int4 not null, address varchar(255), description varchar(255), joinDate date, userName varchar(255), primary key (userId))
                Mar 26, 2014 3:49:07 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
                INFO: HHH000230: Schema export complete
                Hibernate: insert into USER_DETAILS (address, description, joinDate, userName, userId) values (?, ?, ?, ?, ?)
                Hibernate: select userdetail0_.userId as userId1_0_0_, userdetail0_.address as address2_0_0_, userdetail0_.description as descript3_0_0_, userdetail0_.joinDate as joinDate4_0_0_, userdetail0_.userName as userName5_0_0_ from USER_DETAILS userdetail0_ where userdetail0_.userId=?
                User Name Retrieved is Avinash
    

    第二次运行上面的代码时,hibernate不会创建表。以下是第二轮的输出

        Mar 26, 2014 3:50:52 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
        INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
        Mar 26, 2014 3:50:52 PM org.hibernate.Version logVersion
        INFO: HHH000412: Hibernate Core {4.3.4.Final}
        Mar 26, 2014 3:50:52 PM org.hibernate.cfg.Environment <clinit>
        INFO: HHH000206: hibernate.properties not found
        Mar 26, 2014 3:50:52 PM org.hibernate.cfg.Environment buildBytecodeProvider
        INFO: HHH000021: Bytecode provider name : javassist
        Mar 26, 2014 3:50:52 PM org.hibernate.cfg.Configuration configure
        INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
        Mar 26, 2014 3:50:52 PM org.hibernate.cfg.Configuration getConfigurationInputStream
        INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
        Mar 26, 2014 3:50:52 PM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
        WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
        Mar 26, 2014 3:50:52 PM org.hibernate.cfg.Configuration doConfigure
        INFO: HHH000041: Configured SessionFactory: null
        Mar 26, 2014 3:50:52 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
        WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
        Mar 26, 2014 3:50:52 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
        INFO: HHH000401: using driver [org.postgresql.Driver] at URL [jdbc:postgresql://localhost:5432/hibernatedb]
        Mar 26, 2014 3:50:52 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
        INFO: HHH000046: Connection properties: {user=postgres, password=****}
        Mar 26, 2014 3:50:52 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
        INFO: HHH000006: Autocommit mode: false
        Mar 26, 2014 3:50:52 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
        INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
        Mar 26, 2014 3:50:52 PM org.hibernate.dialect.Dialect <init>
        INFO: HHH000400: Using dialect: org.hibernate.dialect.PostgreSQL9Dialect
        Mar 26, 2014 3:50:52 PM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
        INFO: HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
        Mar 26, 2014 3:50:52 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
        INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
        Mar 26, 2014 3:50:52 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
        INFO: HHH000397: Using ASTQueryTranslatorFactory
        Mar 26, 2014 3:50:52 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
        INFO: HHH000227: Running hbm2ddl schema export
        Hibernate: drop table USER_DETAILS cascade
    

    线条说“&#34; drop table USER_DETAILS cascade&#34; 请建议或帮助我解决问题。在此先感谢

5 个答案:

答案 0 :(得分:2)

尝试在主方法结束时关闭sessionFactory。

public static void main(String[] args) {

UserDetails userDetails = new UserDetails();
userDetails.setUserId(1);
userDetails.setUserName("Avinash");
userDetails.setAddress("Rajeev Nagar");
userDetails.setJoinDate(new Date());
userDetails.setDescription("Software Engineer");

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(userDetails);
session.getTransaction().commit();
session.close();

userDetails=null;
session = sessionFactory.openSession();
session.beginTransaction();
userDetails = (UserDetails)session.get(UserDetails.class, 1);
System.out.println("User Name Retrieved is " + userDetails.getUserName());
session.close();
sessionFactory.close();
}

答案 1 :(得分:0)

请勿自行设置ID。 由于您目前正在将ID硬编码为1,因此第二次失败。

以下代码会自动生成ID。

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ID")
private Long id;

答案 2 :(得分:0)

根据您的代码,请先告诉我: -

1.您是否尝试创建表格或尝试在表格中插入记录,因为在查看代码后我可以说您正在将记录插入表格中。

Hibernate插入: -

  1. 当您尝试使用任何表格插入任何记录时 hibernate主键由hibernate本身唯一分配 为您记录。 (你不必担心它的统一ID 记录。)
  2. 在您的代码中,您正确定义了实体,但没有指定实体 实体主键的自动增量(表)
  3. 您的代码: -

    @Entity
    @Table (name="USER_DETAILS")
    public class UserDetails {
    
    @Id
    private int userId;
    

    应该更正(以便hibernate本身使用唯一键处理插入): -

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "ID")
    private Long id;
    

    您的代码中的第三个错误点是您自己分配主键,这也是错误的 -

    UserDetails userDetails = new UserDetails();
    userDetails.setUserId(1);
    

    如果您有进一步的疑问或怀疑,请告诉我们。

答案 3 :(得分:0)

干得好,问题出现了如下所示

session.getSessionFactory().close();

我有同样的问题。它已经修好了;)

答案 4 :(得分:0)

我今天遇到了同样的问题。这就是我在主要方法中所做的:

        Configuration configuration = new Configuration();
        configuration.configure();
        final ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
            configuration.getProperties()).build();
        SessionFactory  sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        Session session = sessionFactory.openSession();
        session.beginTransaction(); 
        ...
        ...
        session.close();
        session.getSessionFactory().close();
        StandardServiceRegistryBuilder.destroy(serviceRegistry);

我还在我的进程列表中检查到我之前的运行后台中仍然没有运行java进程。结束这些正在运行的进程后,一切都恢复正常。