我想转换以下SQL查询:
select * from region_tree country left outer join region_tree region
on country.REG_CODE_PAR=region.REG_CODE
and region.LFT < country.LFT
and region.RGT > country.RGT
and region.REG_CODE_PAR = 'ALL'
and COUNTRY.STATUS_CODE = 'A'
and REGION.STATUS_CODE = 'A
进入基于JPA Crtieria的查询。
我创建了一个代表自联接的实体:
@Entity
@Table(name = "REGION_TREE")
public class RegionTree implements Serializable {
... some other attributes
@ManyToOne
@JoinColumn(name = "REG_CODE_PAR")
private RegionTree region;
... getters and setters
}
我使用以下代码创建JPA查询
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<RegionTree> cq = cb.createQuery(RegionTree.class);
Root<RegionTree> e = cq.from(RegionTree.class);
Join<RegionTree, RegionTree> r = e.join("region", JoinType.LEFT);
Predicate p1 = cb.greaterThan(e.get("lft").as(Integer.class), r.get("lft").as(Integer.class));
Predicate p2 = cb.lessThan(e.get("rgt").as(Integer.class), r.get("rgt").as(Integer.class));
Predicate p3 = cb.equal(e.get("statusCode"), "A");
Predicate p4 = cb.equal(r.get("statusCode"), "A");
Predicate p5 = cb.equal(r.get("regCodePar"), "ALL");
cq.where(p1,p2,p3,p4,p5);
TypedQuery<RegionTree> tq = em.createQuery(cq);
l = tq.getResultList();`
这是我运行这段代码时由Hibernate自动生成的查询。
select
regiontree0_.REG_CODE as REG1_7_,
regiontree0_.LFT as LFT7_,
regiontree0_.NAME as NAME7_,
regiontree0_.REG_CODE_PAR as REG4_7_,
regiontree0_.RGT as RGT7_,
regiontree0_.STATUS_CODE as STATUS6_7_
from
REGION_TREE regiontree0_
left outer join
REGION_TREE regiontree1_
on regiontree0_.REG_CODE_PAR=regiontree1_.REG_CODE
where
cast(regiontree0_.LFT as integer)>cast(regiontree1_.LFT as integer)
and cast(regiontree0_.RGT as integer)<cast(regiontree1_.RGT as integer)
and regiontree0_.STATUS_CODE=?
and regiontree1_.STATUS_CODE=?
and regiontree1_.REG_CODE_PAR=?
我尝试了多种方法,包括删除cq.where
代码行,但生成的查询与原始查询不匹配。我配置错了吗?
答案 0 :(得分:1)
创建连接后尝试调用cq.select(r);
。如果没有cq.select()
,则上次cq.from()
调用的结果将用作选择根。