我有一个hibernate项目,我想自动创建表。如果已经创建了一个表,那么我在Entity类中添加一个新字段然后我想在表中创建一个新字段而不删除该表的数据。我在下面给出了我的源代码。
的hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">1234</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<mapping class="Inventory" package="com.mycompany.testhibernate"/>
</session-factory>
</hibernate-configuration>
EntityClass
package com.mycompany.testhibernate;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Inventory implements Serializable {
private Integer id;
private String itemName;
private String itemNote;
private Integer quantity;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public int getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getItemName() {
return this.itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getItemNote() {
return itemNote;
}
public void setItemNote(String itemNote) {
this.itemNote = itemNote;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public int getQuantity() {
return this.quantity;
}
}
答案 0 :(得分:1)
您尝试使用此选项吗?
<property name="hibernate.hbm2ddl.auto">update</property>
应根据您的bean更新您的DDL
hbm2ddl.auto更新:
如果值是更新,则hibernate检查表和 列。如果表不存在则会创建一个新表,如果是 列不存在它为它创建新列。
同时将属性更改为:
<mapping class="com.mycompany.testhibernate.Inventory"/>