Java 通过Hibernate关联表检索对象?
有三个表A、B、A_B_关系,最后一个是A和B的关联表。Java 通过Hibernate关联表检索对象?,java,mysql,hibernate,Java,Mysql,Hibernate,有三个表A、B、A_B_关系,最后一个是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” @Entity @Table(name = "A") public class A { @
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”
@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.id=r.A\u id上的左连接A\u B\u关系r.B\u id=B.id上的左连接B,但我不确定如何通过hibernate实现它
提前谢谢。既然你没有描述A和B之间的关系,是不是一个一个一个多个一个一个多个我假设它是A侧面的一个多个。因为每个A只与一个B相关,你需要第三个表来进行连接,所以每个A都与一个B相关,而B可以与多个A相关
@实体
@表(name=“A”)
公共A类{
@GenericGenerator(name=“idGenerator”,strategy=“increment”)
@身份证
@GeneratedValue(generator=“idGenerator”)
@列(name=“id”,unique=true,nullable=false)
私有整数id;
@列(name=“value\u a”)
私有字符串值a;
@joinTable(name=“A\u B\u关系”,joinColumns=@JoinColumn(name=“A\u id”),
inverseJoinColumns=@JoinColumn(name=“b_id”))
@ManyToMany(fetch=FetchType.EAGER)
私人名单b;
}
很抱歉,缺少关键点。很多。对于A的特定实例,应该有很多B映射。谢谢,这是正确的,我更新了@JoinColumn
条件。很抱歉缺少关键点。很多。对于A的特定实例,应该有许多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;
@joinTable(name="A_B_relation",joinColumns=@JoinColumn(name="a_id"),
inverseJoinColumns=@JoinColumn(name="b_id"))
@ManyToMany(fetch=FetchType.EAGER)
private List<B> b;
}