2016-01-25 49 views
1

如何使用条件查询来应用左连接,我只能在Internet上查找内连接条件。Hibernate criteriaQuery - 左连接

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

除法是一个存在于A类中的实体,这是返回我的内部连接结果。我想申请左连接上划分实体:

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

表的数据:

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; 

LEFT JOIN结果:

+----+-------------+-------------+------+------+ 
| 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 | 
+----+-------------+-------------+------+------+ 
+0

你可以使用'where'条款的加入后,但如果你表现出的分贝结构,一些样本数据,你想要的结果,你会得到更好的答案。 – davejal

回答

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