我想要这个SQL:
select * from tableA
left outer join joinAB on tableA.id = joinAB.a_id
left outer join tableB on tableB.id = joinAB.b_id and tableB.otherCol = 4;
使用这样的模型:
class TableA {
@OneToMany
@JoinTable(
name = "joinAB",
joinColumns = @JoinColumn(name = "a_id"),
inverseJoinColumns = @JoinColumn(name = "b_id")
)
private Set<TableB> bs;
}
我正在尝试编写一个Criteria,它将返回所有TableAs及其bs,但也包含as而不包含任何bs。因此左外连接。 tableB很大,所以otherCol实际上是一个索引列,我需要限制它以防止MySQL进行全表扫描。
我正在使用这个标准:
this.getSession().createCriteria(TableA.class)
.createAlias("bs", "bs", CriteriaSpecification.LEFT_JOIN,
Restrictions.eq("bs.otherCol", 4));
但我最终得到了这个SQL:
select * from tableA this_ left outer join joinAB bs5_
on this_.id=bs5_.a_id and ( bs1_.otherCol=4 )
left outer join tableB bs1_ on bs5_.b_id=bs1_.id and ( bs1_.otherCol=4 )
所以你看到它在连接表上添加了一个无意义的限制(生成的SQL甚至不会执行。)
如何让它做正确的事?
答案 0 :(得分:1)
Criteria crit = session.createCriteria(TableA.class);
crit.createCriteria(“joinAB”,“AB”,JoinType.LEFT_OUTER_JOIN);
crit.createCriteria(“tableB”,“TB”,JoinType.LEFT_OUTER_JOIN,Restrictions.eq(“TB.otherCol”,“4”));
crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);