Hibernate自动创建旧表/ drop

时间:2015-10-19 18:03:20

标签: java hibernate jpa jpa-2.1

每当我运行此代码时,hibernate将删除当前表/创建一个新表并再次填充它:

public static void main(String[] args) {
   UserRepository userRepository = UserRepository.getInstance();
   UserEntity user = new UserEntity("foo", "foo@example.com", 4321);
   userRepository.save(user);
}

的persistence.xml:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <persistence-unit name="web" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties>
      <property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/web"/>
      <property name="javax.persistence.jdbc.user" value="postgres"/>
      <property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
      <property name="javax.persistence.jdbc.password" value="1234"/>
      <property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
      <property name="javax.persistence.schema-generation.database.action" value="update"/>
      <property name="hibernate.hbm2ddl.auto" value="update"/>
    </properties>
  </persistence-unit>
</persistence>

例如,如果我运行main一次,我会在数据库中找到:

id    |     username     |    e-mail        |    bar
1     |        foo       | foo@example.org  |   4321

正如预期的那样,如果我更改UserEntity user = new UserEntity("bar", "bar@example.com", 4321);并再次运行:

数据库只会显示:

id    |     username     |    e-mail        |    bar
1     |        bar       | bar@example.org  |   4321

自从我使用以来,hibernate不应该保留数据库吗?

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

2 个答案:

答案 0 :(得分:1)

您无需使用属性javax.persistence.schema-generation.database.action。此属性设置架构的生成策略,即放置/创建行为,如https://docs.oracle.com/javaee/7/tutorial/persistence-intro005.htm

中所述

答案 1 :(得分:1)

您拥有此属性javax.persistence.schema-generation.database.action

此属性的值为nonecreatedrop-and-createdrop

update不是此属性的有效值。

此外,您已拥有hibernate.hbm2ddl.auto属性,因此我建议您删除第一个属性。