自我加入条件查询

时间:2018-03-13 10:20:57

标签: java jpa orm criteria-api self-join

所以我有一张名为' User'有字段

  • 用户id
  • 的userName
  • supervisorId

我想获取特定用户的主管的userName。

List<BitmapImage> Images = new List<BitmapImage>
{
    new BitmapImage(new Uri(@"/Images/Car.bmp", UriKind.Relative)),
};

现在我还有许多其他条件,除了这个supervisorId。所以我必须使用相同的条件查询。

感谢。

2 个答案:

答案 0 :(得分:1)

Criteria API适用于您需要build queries dynamically时,您应该始终记住它基于遍历实体。

你需要的是一个像这样的简单SQL查询:

select sp.userName
from users u
join users sp on sp.userId = u.supervisorId
where userId = ?

仅仅因为你使用了JPA和Hibernate,it does not mean that you should not use SQL queries

如果map the supervisor as a @ManyToOne association

,可以非常轻松地编写Criteria API查询
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="supervisorId", referencedColumnName="userId")
private User supervisor;

然后,联接变为:

Join<User, User> selfJoin = rootUser.join("supervisor", JoinType.LEFT);

答案 1 :(得分:0)

我实现并为我工作的示例。这不是确切的代码,但此代码应该可以工作。我尚未在同一实体中创建引用变量。

SQL

select right.* from MyTable left, MyTable right where left.subjectid = 7 and left.studentid = right.studentid
and left.subjectid != right.subjectid;

条件代码

CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<MyTable]> criteria = builder.createQuery(MyTable.class);
Root<MyTable> MyTableRootLeft = criteria.from(MyTable.class);
Root<MyTable> MyTableRootRight = criteria.from(MyTable.class);
Predicate selfJoinPredicate = 
builder.and(
            builder.equal(MyTableRootLeft.get(subjectid), subjectid),
            builder.equal(MyTableRootLeft.get(studentid),MyTableRootRight.get(studentid)),
              builder.notEqual(MyTableRootLeft.get(subjectid),
MyTableRootRight.get(subjectid)));