有三个表 A,B,A_B_relation,最后一个是A和B的关联表。
Columns of table A: id, value_a
Columns of table B: id, value_b
Columns of table A_B_relation: id, a_id, b_id
您可以在下面找到A和B的映射类。请注意,A类中有一个字段“B b”。
@Entity
@Table(name = "A")
public class A {
@GenericGenerator(name = "idGenerator", strategy = "increment")
@Id
@GeneratedValue(generator = "idGenerator")
@Column(name = "id", unique = true, nullable = false)
private Integer id;
@Column(name = "value_a")
private String valueA;
private B b;
}
@Entity
@Table(name = "B")
public class B {
@GenericGenerator(name = "idGenerator", strategy = "increment")
@Id
@GeneratedValue(generator = "idGenerator")
@Column(name = "id", unique = true, nullable = false)
private Integer id;
@Column(name = "value_b")
private String valueB;
}
是否有可能在hibernate中通过session.get("A", id)
初始化b来获取实例A?正如我所知,应该有表连接,例如A a left join A_B_relation r on a.id = r.a_id left join B b on r.b_id = b.id
,但我不确定如何通过hibernate实现它。
提前致谢。
答案 0 :(得分:0)
因为你没有描述A和B之间的关系,所以是OneToOne ManyToOne OneToMany ManyToMany我将假设它是A的一侧的ManyToOne,因为每个A只与一个B相关,你需要第三个表进行连接,使每个A与一个B相关,但B可以与许多A(s)相关
@Entity
@Table(name = "A")
public class A {
@GenericGenerator(name = "idGenerator", strategy = "increment")
@Id
@GeneratedValue(generator = "idGenerator")
@Column(name = "id", unique = true, nullable = false)
private Integer id;
@Column(name = "value_a")
private String valueA;
@joinTable(name="A_B_relation",joinColumns=@JoinColumn(name="a_id"),
inverseJoinColumns=@JoinColumn(name="b_id"))
@ManyToMany(fetch=FetchType.EAGER)
private List<B> b;
}