如何使Hibernate不丢弃表

时间:2011-07-07 13:34:14

标签: hibernate

我正在使用hibernate,每当我尝试添加记录时,它都会丢弃表并再次添加它。它从不使用现有的表并对其进行更改。

这是我hibernate.cfg.xml的相关部分:

<hibernate-configuration>
<session-factory>
  <property name="hibernate.connection.driver_class">org.apache.derby.jdbc.ClientDriver</property>
  <property name="hibernate.connection.url">jdbc:derby://localhost:1527/sample</property>
  <property name="hibernate.connection.username">user</property>
  <property name="hibernate.connection.password">password</property>
  <property name="hibernate.connection.pool_size">10</property>
  <property name="show_sql">true</property>
  <property name="dialect">org.hibernate.dialect.DerbyDialect</property>
  <property name="hibernate.hbm2ddl.auto">update</property>
  <property name = "current_session_context_class">thread</property>
  <!-- Mapping the entities -->
<mapping class="inputDetails.Table1"/>
<mapping class="inputDetails.Table2"/>


  <!--mapping resource="contact.hbm.xml"/-->
</session-factory>
</hibernate-configuration>

这是我保存数据的方式:

SessionFactory factory = new Configuration().configure().buildSessionFactory();
    Session session = factory.getCurrentSession();
    session.beginTransaction();
//...
session.save(newrecord)
session.getTransaction().commit();

5 个答案:

答案 0 :(得分:18)

<property name="hibernate.hbm2ddl.auto">update</property>
每次创建会话工厂时,

都会告诉hibernate更新数据库模式。

并且

SessionFactory factory = new Configuration().configure().buildSessionFactory();

建立一个新的会话工厂。

在应用程序生命周期内,SessionFactory只应构建一次。它应该创建一次然后重用。您是否阅读过hibernate reference manual

答案 1 :(得分:1)

你确定它被覆盖了还是没有提交?我的意思是你提交你的交易吗?

也许尝试以下几行:

try {
    factory.getCurrentSession().beginTransaction();

    // Do some work
    factory.getCurrentSession().load(...);
    factory.getCurrentSession().persist(...);

    factory.getCurrentSession().getTransaction().commit();
}
catch (RuntimeException e) {
    factory.getCurrentSession().getTransaction().rollback();
    throw e; // or display error message
}

答案 2 :(得分:1)

希望这可以帮到你

AnnotationConfiguration config = new AnnotationConfiguration();

config.addAnnotatedClass(Employee.class);
config.configure("hibernate.cfg.xml");
new SchemaExport(config).drop(false, false);

答案 3 :(得分:1)

我有

<property name="hibernate.hbm2ddl.auto" value="create-drop" />
<property name="hibernate.hbm2ddl.import_files" value="META-INF/import.sql" />

我第一次部署。这创建了我想要的架构并用数据填充它。我第二次换到

<property name="hibernate.hbm2ddl.auto" value="update" />

并重新部署。表格显然已被删除。我在第一次部署时切换到create并继续使用update进行重新部署。这个时间表没有被删除,数据保持不变。

答案 4 :(得分:0)

如果您使用注释,请尝试以下操作:

Properties hibernateProperties = new Properties();
// your props ...
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", "update");

// or use Environment.HBM2DDL_AUTO from org.hibernate.cfg.Environment
hibernateProperties.setProperty(Environment.HBM2DDL_AUTO, "update");
相关问题