gpt4 book ai didi

java - 我无法从 hibernate 项目自动创建表

转载 作者:行者123 更新时间:2023-12-01 09:14:54 25 4
gpt4 key购买 nike

我有一个 hibernate 项目,我想自动创建表。如果已经创建了一个表,那么我在实体类中添加一个新字段,然后我想在表中创建一个新字段而不删除表的数据。我在下面给出了我的源代码。

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>

实体类

     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;
}


}

最佳答案

您尝试过此选项吗?

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

应该根据您的bean更新您的DDL

hbm2ddl.auto update :

If the value is update then hibernate checks for the table and columns. If table doesn’t exist then it creates a new table and if a column doesn’t exist it creates new column for it.

还将属性更改为:

<mapping class="com.mycompany.testhibernate.Inventory"/>

关于java - 我无法从 hibernate 项目自动创建表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40628810/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com