简体   繁体   English

通过Hibernate的关联表检索对象?

[英]retrieve object through associate table by Hibernate?

There are three tables A, B, A_B_relation, and the last one is the associate table of A and B. 有三个表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

You may find the mapping classes for A and B as below. 您可能会发现A和B的映射类如下。 Please note that there is a field "B b" in class A. 请注意,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;
}

Is it possible to get instance A with initialized b by session.get("A", id) in hibernate? 是否可以通过休眠中的session.get("A", id)获取实例B初始化为b的实例A? As I known, there should be tables join such as A a left join A_B_relation r on a.id = r.a_id left join B b on r.b_id = b.id , but I'm not sure how to implement it by hibernate. 如我所知,应该有一些表连接,例如A a left join A_B_relation r on a.id = r.a_id left join B b on r.b_id = b.id ,但是我不确定如何通过休眠实现它。

Thanks in advance. 提前致谢。

since you didn't describe the relation between A and B , is it OneToOne ManyToOne OneToMany ManyToMany i will assume that it is ManyToOne from the side of A. since each A is related to only one B and you needed a third table to make the join so each A is related to one B but B can be related to many A(s) 因为您没有描述A和B之间的关系,所以它是OneToOne ManyToOne OneToMany ManyToMany我会假设它是从A侧面来看的。因为每个A仅与一个B相关,并且您需要第三个表来制作A联接,因此每个A与一个B相关,但是B可以与许多A相关

  @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;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM