本文介绍了双向一对多连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一些与JoinTables一起工作的双向一对多关联问题。这是我得到的:



A类:

  @OneToMany 
@JoinTable(name =join_table,
JoinColumns = {@ JoinColumn(name =a_id)},
inverseJoinColumns = {@ JoinColumn(name =b_id)}

@Cascade(org.hibernate.annotations.CascadeType.ALL)
public Set< B> getBs(){
return bs;

$ / code>

B类:

  @ManyToOne 
@JoinTable(name =join_table,
joinColumns = {@ JoinColumn(name =b_id,insertable = false,updatable = false) },
inverseJoinColumns = {@ JoinColumn(name =a_id,insertable = false,updatable = false)})
public getA(){
return a;





$ b如果我创建A和B的实例,将B的实例添加到A并保存。有用。但是,当我重新加载A的实例并尝试访问B的集合时,它会抛出LazyInitializationError,并显示消息非法访问加载集合。



我在哪里错了? :)任何人都可以指出我使用连接表的双向关联的例子。在所有权保留给A类的情况下,我已经通过hibernate.org上的文档进行了搜索,但我似乎找不到它。



-Daniel

解决方案

您的映射是正确的,这就是为什么条目正在保存在数据库中。抓取中的问题因为

为了解决它,修改类A的映射为,

  @OneToMany(fetch = FetchType.LAZY)
@JoinTable(name =join_table,
joinColumns = {@ JoinColumn(name =a_id)},
inverseJoinColumns = {@ JoinColumn(name =b_id)}

@Cascade(org.hibernate.annotations.CascadeType.ALL)
public Set< B> getBs(){
return bs;
}

这将触发对表B的额外查询并初始化集合。它可能会影响性能,具体取决于被告表中的条目数量。



阅读API 获取更多信息。


I'm having some issues getting a bidirectional one-to-many association working with JoinTables. This is what I got:

Class A:

@OneToMany
@JoinTable(name="join_table",
    JoinColumns={@JoinColumn(name="a_id")},
    inverseJoinColumns={@JoinColumn(name="b_id")}
)
@Cascade(org.hibernate.annotations.CascadeType.ALL)
public Set<B> getBs() {
    return bs;
}

Class B:

@ManyToOne
@JoinTable(name="join_table",
    joinColumns={@JoinColumn(name="b_id", insertable=false,updatable=false)},
    inverseJoinColumns={@JoinColumn(name="a_id", insertable=false,updatable=false)})
public A getA() {
    return a;
}

If I create a instance of A and B, add the instance of B to A and save. It works. But when I reload the instance of A and try and access the set of Bs it throws a LazyInitializationError with the message "illegal access to loading collection ".

Where am I going wrong here? :) Can anybody point me to a example of bidirectional association which uses a join table. And where the ownership is kept to Class A, I have searched though the documentation at hibernate.org but I cant seem to find it.

-Daniel

解决方案

Your mapping are proper and that's why the entry is getting saved in the Database. The issue in fetching is because of the Lazy Initialization.

To solve it modify mapping of the class A as,

@OneToMany(fetch=FetchType.LAZY)
@JoinTable(name="join_table",
    joinColumns={@JoinColumn(name="a_id")},
    inverseJoinColumns={@JoinColumn(name="b_id")}
)
@Cascade(org.hibernate.annotations.CascadeType.ALL)
public Set<B> getBs() {
    return bs;
}

This will fire an additional query to the table B and initialize the collection. It might affect the performance depending on the no of entries in your defendant table.

Read the API here for more information.

这篇关于双向一对多连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 07:43