【问题标题】:Hibernate criteriaQuery - left join休眠条件查询 - 左连接
【发布时间】:2016-05-02 06:55:19
【问题描述】:

如何使用条件查询应用左连接,我只能在互联网上找到内连接条件。

        Criteria cr = this.sessionFactory.getCurrentSession().createCriteria(A.class, "a").createAlias("a.division", "division");                  
        List<A> list = cr.list();

division 是 A 类中的一个实体,这将返回内部连接结果。我想在部门实体上应用左连接:

select * from A as a left join divisions as division on division.id = a.id;

表A数据:

    id  name        division_id
    1   first name  1
    3   sec name    2
    6   fourth name 2
    5   3rd name    NULL

分表数据:

    id  type
    1   F
    2   G

内连接:

select * from A as a inner join division where a.division_id = division.id

内连接结果:

+----+-------------+-------------+----+------+
| id | name        | division_id | id | type |
+----+-------------+-------------+----+------+
|  1 | first name  |           1 |  1 | F    |
|  3 | sec name    |           2 |  2 | G    |
|  6 | fourth name |           2 |  2 | G    |
+----+-------------+-------------+----+------+

左连接查询:

select * from A as a left join division on division.id = a.division_id;

左连接结果:

+----+-------------+-------------+------+------+
| id | name        | division_id | id   | type |
+----+-------------+-------------+------+------+
|  1 | first name  |           1 |    1 | F    |
|  3 | sec name    |           2 |    2 | G    |
|  6 | fourth name |           2 |    2 | G    |
|  5 | 3rd name    |        NULL | NULL | NULL |
+----+-------------+-------------+------+------+

【问题讨论】:

  • 你可以在join之后使用where子句,但是如果你展示了db结构,一些样本数据和你想要的结果,你会得到更好的答案。

标签: mysql hibernate join


【解决方案1】:

如果你想左加入,你可以在createAlias中提及。默认为inner join

Criteria cr = this.sessionFactory.getCurrentSession().createCriteria(A.class, "a")
      .createAlias("a.division", "division", CriteriaSpecification.LEFT_JOIN);     // Add join type            
List<A> list = cr.list();

CriteriaSpecification.LEFT_JOIN

【讨论】:

    猜你喜欢
    • 2014-09-24
    • 1970-01-01
    • 2015-04-17
    • 1970-01-01
    • 1970-01-01
    • 2015-02-06
    • 2012-12-22
    • 1970-01-01
    • 2011-06-08
    相关资源
    最近更新 更多