gpt4 book ai didi

java - Hibernate Cascade 来自另一个数据库的另一个 ID

转载 作者:行者123 更新时间:2023-12-01 09:17:07 28 4
gpt4 key购买 nike

例如,我有 A 类并级联到 B:

public class A{

private String id;
private Set<B> bs = new HashSet<B>(0);

@Id
@GenericGenerator(name = "seq_id", strategy = generators.SequenceIdGenerator")
@GeneratedValue(generator = "seq_id")
@COLUMN(name="id" unique = true, nullable = false, length = 28)
public void getId(){
return this.id;
}

@OneToMany(fetch = FetchType.LAZY, mappedBy = "A")
@Cascade({CascadeType.SAVE_UPDATE, CascadeType.DELETE, CascadeType.PERSIST})
public void getBs(){
return bs;
}
}

我有 B,它有自己的 id 和一个包含 A 的 id 的列

public class B

String id;
String aId;
A a;

@Id
@GenericGenerator(name = "seq_id", strategy = "generators.SequenceIdGenerator")
@GeneratedValue(generator = "seq_id")
@Column(name = "ID", unique = true, nullable = false, length = 28)
public String getId() {
return this.id;
}

@Column(name = "A_ID", nullable = false, length = 28)
public String getAId() {
return aId;
}

public void setAId(String aId) {
this.aId = aId;
}

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "A_ID", nullable = false, insertable = false, updatable = false)
@MapsId("aId")
public Admission getAdmission() {
return this.admission;
}

public void setAdmission(Admission admission) {
this.admission = admission;
}

如何在保存 A 时自动分配 aId?我想要设置 aId,但总是收到错误消息,提示 A_ID 不能设置为 null。

谢谢!

最佳答案

在共享映射中使用派生标识符时,您不仅需要在关系中添加 @MapsId 注解,还需要使用 @Id 对引用关系 ID 的字段进行注解> 注释。

看看如何做(省略 setter ):

public class B {
String id;
String aId;
A a;

@Id
@GenericGenerator(name = "seq_id", strategy = "generators.SequenceIdGenerator")
@GeneratedValue(generator = "seq_id")
@Column(name = "ID", unique = true, nullable = false, length = 28)
public String getId() {
return this.id;
}

@Id
public String getAId() {
return aId;
}

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "A_ID", nullable = false)
@MapsId("aId")
public A getA() {
return this.a;
}
}

另一个错误是您将关系注释为 updatable = falseinsertable = false,从而使持久性提供程序忽略将此字段写入数据库。

关于java - Hibernate Cascade 来自另一个数据库的另一个 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40466400/

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