gpt4 book ai didi

java - Spring 启动 JPA : remove column on entity change

转载 作者:可可西里 更新时间:2023-11-01 07:55:48 26 4
gpt4 key购买 nike

我尝试使用 spring-boot-starter-data-jpa 从 java 类在 MySQL 数据库中创建表。它工作得很好,除非我在 java 类中更改/删除列名。这里有一个例子:

我有一个名为“Staff”的类,其中包含 2 个字段:id、name

@Id 
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private int id;

@Column(name = "name", length = 15)
private String name;

public Staff() {
}
// some setter and getter here

当我运行我的项目时,一个“员工”表完全按照我的意愿生成,包含 2 列:id、name。问题是如果我像这样将“名字”拆分为“名字”和“姓氏”:

@Id 
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private int id;

@Column(name = "firstname", length = 15)
private String firstname;

@Column(name = "lastname", length = 15)
private String lastname;

public Staff() {
}
//some getter and setter here

“员工”表现在包含 4 列(id、姓名、名字、姓氏)而不是 3 列。然后我需要自己删除“姓名”列。有没有办法自动摆脱它?

最佳答案

看起来你在使用:

 spring.jpa.properties.hibernate.ddl-auto=update

78.1 Initialize a database using JPA

spring.jpa.generate-ddl (boolean) switches the feature on and off and is vendor independent. spring.jpa.hibernate.ddl-auto (enum) is a Hibernate feature that controls the behavior in a more fine-grained way. See below for more detail.

You can set spring.jpa.hibernate.ddl-auto explicitly and the standard Hibernate property values are none, validate, update, create, create-drop.

如您所见,没有什么新东西(与 hibernate 不同)

ddl-auto=update - 生成更改它不会删除未映射的列。例如,您可以有一个包含 10 列的表,并且仅映射其中的 3 列,在这种情况下,自动模式可能会删除它们,但对于 hibernate/jpa 完整映射表实体不是强制性的。这是jira票Alter and drop columns with hbm2ddl.auto=update创建于 2011 年 11 月,现在状态为“未修复”。

如果您经常更新数据库(您的域模型已更改),您可以使用 ddl/dml 工具,如 liquibase , flywaydb .您在 xml 文件中描述数据库更改,并执行工具,所有更改将自动应用(自动控制之前已经修改的内容和现在应该修改的内容)。

只是推荐:如果你不想猜测为什么某些东西在生产中被丢弃,最好使用 ddl 工具。 hibernate.ddl-auto 主要用于开发,不用于生产。在生产中,您可以不使用或验证 - 因为它们是安全的。

关于java - Spring 启动 JPA : remove column on entity change,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44962217/

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