Hibernate- manytomany获得所有元素

时间:2017-03-13 14:44:26

标签: hibernate

当我尝试获取所有群组时,如果群组有多对多的关系,我会获得该群组的重复记录

集团实体:

@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.REFRESH)
@JoinTable(name = "sp_yardgroup", schema = "store_documents", 
        joinColumns = @JoinColumn(name = "group_id"), 
        inverseJoinColumns = @JoinColumn(name = "yard"))
@NotFound(action = NotFoundAction.IGNORE)
private List<Store> yards =  new ArrayList<Store>()

GroupYardEntity:

@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "sp_yardgroup", schema = "store_documents",
        joinColumns = @JoinColumn(name = "yard", insertable = false),
        inverseJoinColumns = @JoinColumn(name = "group_id"))
@NotFound(action = NotFoundAction.IGNORE)
public Set<CustomGroup> getGroups() {
    return groups;
}

如果我切换到Lazy fetchType,当我尝试在编辑页面中调用getById方法时,我会得到lazyException,但它会显示正确的列表

@Transactional
public List<CustomGroup> getGroups() {
    Criteria criteria = getSession().createCriteria(CustomGroup.class);
    return criteria.list();
}

知道我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

我弄清楚了,需要添加“@LazyCollection(LazyCollectionOption.FALSE)”

    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.REFRESH)
@JoinTable(name = "sp_yardgroup", schema = "store_documents", 
joinColumns = @JoinColumn(name = "group_id"), 
inverseJoinColumns = @JoinColumn(name = "yard"))
 @LazyCollection(LazyCollectionOption.FALSE)
private List<Store> yards =  new ArrayList<Store>();