每當我運行此代碼,Hibernate會刪除當前表/創建一個新的,再填寫:,Hibernate自動創建表/下降舊
public static void main(String[] args) {
UserRepository userRepository = UserRepository.getInstance();
UserEntity user = new UserEntity("foo", "[email protected]", 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 | [email protected] | 4321
正如預期的那樣,但是如果我改變UserEntity user = new UserEntity("bar", "[email protected]", 4321);
並再次運行:
數據庫將只顯示:
id | username | e-mail | bar
1 | bar | [email protected] | 4321
,因爲我使用不應該冬眠保持數據庫?
<property name="hibernate.hbm2ddl.auto" value="update"/>
感謝您的指定解釋:) – Mansueli