gpt4 book ai didi

java - 如何在 Hibernate 中通过第三个实体将一个实体连接到第二个实体?

转载 作者:行者123 更新时间:2023-11-30 07:12:30 26 4
gpt4 key购买 nike

我想给 C 一个对 A 实例的引用,但 A 拥有的只是 B 实例的外键。B 拥有 C 实例的外键。下面是一个示例。

@Entity
public Class A {

public int id;
public Integer bId;

}

@Entity
public Class B {
public Integer id;
public Integer cId;
}


@Entity
public Class C {
public A a;
public Integer id;
}

如何在 Spring 中使用 Hibernate 注释来实现此目标?

最佳答案

我认为最小的实现应该是这样的(使用 JPA 2.x):

@Entity
class A {
public Integer id;
public Integer bId;
}

@Entity
class B {
public Integer id;
public Integer cId;

@OneToMany
@JoinColumn(name="bId")
private Set<A> a;
}

@Entity
class C {

public Integer id;
@ManyToOne
public A a;

@OneToMany
@JoinColumn(name="cId")
private Set<B> b;

}

或者,如果您想依赖实体引用而不是 id:

@Entity
class A {
public Integer id;

@ManyToOne
public B b;
}

@Entity
class B {
public Integer id;

@ManyToOne
public C c;
}

@Entity
class C {
public Integer id;

@ManyToOne
public A a;
}

关于java - 如何在 Hibernate 中通过第三个实体将一个实体连接到第二个实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39001415/

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