2016-02-17 47 views
0

有三個表A,B,A_B_relation,最後一個是A的關聯表和B.通過Hibernate關聯表檢索對象?

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作爲下面的映射類。請注意,有一個領域「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; 

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

是否有可能在休眠session.get("A", id)獲得實例的初始化與B'據我所知,應該有表連接,如A a left join A_B_relation r on a.id = r.a_id left join B b on r.b_id = b.id,但我不知道如何通過休眠來實現它。

在此先感謝。

+0

對不起,缺少重點。這是ManyToMany。對於A的具體實例,應該有許多B映射。 – Junjie

回答

0

因爲你沒有描述A和B之間的關係,它是OneToOne ManyToOne OneToMany ManyToMany我會認爲它是從A側的ManyToOne,因爲每個A只與一個B有關,而你需要第三個表使聯接所以每個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",[email protected](name="a_id"), 
        [email protected](name="b_id")) 
     @ManyToMany(fetch=FetchType.EAGER) 
     private List<B> b; 
    } 
+0

對不起,缺少重點。這是ManyToMany。對於A的具體實例,應該有許多B映射。 – Junjie

+0

所以你應該有一個B列表對嗎? – achabahe

+0

是的,你說得對,我會試一試。 – Junjie