【发布时间】:2015-01-19 07:43:07
【问题描述】:
我有两个名为 Position 和 Content 的多对多关系表。
映射是collect,因为insert等查询都可以正常工作。
我用
Criteria c = sessionFactory.getCurrentSession().createCriteria(Content.class);
c.add(Restrictions.isEmpty("position"));
获取数据集,这意味着所有内容都没有被任何位置占用。
它工作正常。
然后,我添加:
Criteria c = sessionFactory.getCurrentSession().createCriteria(Content.class);
c.add(Restrictions.isEmpty("position"));
c.createAlias("position", "p");
c.add(Restrictions.eq("p.id", 100));
这意味着获取所有内容都没有被位置 100 占用。
我得到一个空的回报。
有些人建议我使用:
c.createAlias("position", "p");
c.add(Restrictions.not(Restrictions.eq("p.id", 100)))
它有效,但结果如下 sql:
SELECT * FROM `position_has_content` WHERE content_id not in (select content_id from `position_has_content` where position_id = 100)
虽然我需要这样的结果:
SELECT * FROM `content` WHERE `content`.id not in (select content_id from `position_has_content` where position_id = 100)
有什么不同。
我可以知道我在这里错过了什么吗?
问题解决后我会继续更新。
案例中的表格如下:
position Position_has_content content
id position_id id
content_id
所以,这是多对多的情况,它们已经在休眠中正确映射。
映射关系阶段:
@ManyToMany(mappedBy = "content")
private Set<Position> position;
-------------------------------------------------------------
@ManyToMany(fetch = FetchType.EAGER,cascade=CascadeType.ALL)
@JoinTable(name = "position_has_content", joinColumns = {
@JoinColumn(name = "position_id") },
inverseJoinColumns = { @JoinColumn(name = "content_id") })
@OrderBy("position")
private Set<Content> content;
映射是正确的,因为所有其他操作(没有“不在”的普通EAGER查询,两侧的插入,删除)都可以正常工作。
【问题讨论】:
-
条件 c = sessionFactory.getCurrentSession().createCriteria(Content.class); c.createAlias("位置", "p"); c.add(Restrictions.eq("p.id", 100));列表 nc = c.list(); List
idList = new ArrayList (); for(内容续:nc){ idList.add(cont.getId());条件 c2 = sessionFactory.getCurrentSession().createCriteria(Content.class).setFetchMode("position", FetchMode.SELECT); if(nc.size()!=0) c2.add(Restrictions.not(Restrictions.in("id",idList)));返回 c2.list();我知道这不是高效和有效的,所以有什么想法可以帮助吗?谢谢。
标签: hibernate hibernate-criteria