gpt4 book ai didi

hibernate - jpa实体不更新数据库中的关系操作

转载 作者:行者123 更新时间:2023-12-02 20:59:05 25 4
gpt4 key购买 nike

我将组件对象映射到 componentMeta 对象,并且我设置了cascade(javax.persistence.CascadeType) action = all,但数据库中的关系操作仍然是Restrict(它没有更新为级联)

这里是组件对象:

@Entity
@Table(name = "component")
public class Component {

private int idComponent;
private List<ComponentMeta> componentMetas;

public Component() {
}

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public int getIdComponent() {
return this.idComponent;
}

public void setIdComponent(int idComponent) {
this.idComponent = idComponent;
}

@OneToMany(mappedBy = "component", cascade = CascadeType.ALL)
public List<ComponentMeta> getComponentMetas() {
return this.componentMetas;
}

public void setComponentMetas(List<ComponentMeta> componentMetas) {
this.componentMetas = componentMetas;
}
}

和 ComponentMeta 对象:

@Entity
@Table(name = "ComponentMeta")
public class ComponentMeta {

private int idComponentMeta;
private Component component;

public ComponentMeta() {
}

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "idComponentMeta", unique = true, nullable = false)
public int getIdComponentMeta() {
return idComponentMeta;
}

public void setIdComponentMeta(int idComponentMeta) {
this.idComponentMeta = idComponentMeta;
}

@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "idComponent")
public Component getComponent() {
return component;
}

public void setComponent(Component component) {
this.component = component;
}
}

数据库中有关系 Action 的图片(未更新为级联): enter image description here

我在 Spring Boot 中的 hibernate 配置(application.properties):

spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

为什么关系操作不会自动更新为级联?

最佳答案

如果你想让hibernate在外键上生成ON DELETE CASCADE,你需要将@OnDelete放在@OneToMany一侧:

@OneToMany(mappedBy = "component", cascade = CascadeType.ALL)
@OnDelete(action = OnDeleteAction.CASCADE)

关于hibernate - jpa实体不更新数据库中的关系操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39203059/

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