2016-09-28 35 views
0

我確實有一個名爲「Address」的簡單實體,它具有由自己定義的一些屬性和關係,以及一些由某些超類繼承的屬性。Criteria API createAlias在包含空值的列上殺死查詢

public class Base { 
    private UUID id; 
    private Date createdAt; 
    @NotNull 
    private User createdBy; // User is a related Entity that cannot be null 
    private DataImport dataImport; // DataImport is another related entity that can be null 
    //getter & setter 
} 

public class Address extends Base { 
    private String street; 
    @NotNull 
    private Country country; // related entity that can't be null 
    //getter & setter 
} 

我試圖實現與使用標準API一個查詢,我希望得到像含街道和createdAt所有簡單的屬性地址對象的列表。同時,我只想要相關實體的ID(如果存在):createdBy.id,dataImport.id和country.id。

我幾乎沒有使用下列標準查詢:

entityManager.getDelegate().createCriteria(Address.class).add(criteriaExample) 
.excludeZeroes() 
.createAlias("createdBy", "subcreatedBy") 
.createAlias("country", "subcountry") 
.setProjection(Projections.projectionList().add(Projections.property("id").as("id")) 
    .add(Projections.property("createdAt").as("createdAt")) 
    .add(Projections.property("street").as("street")). 
    .add(Projections.property("subcreatedBy.id").as("createdBy.id")) 
    .add(Projections.property("subcountry.id").as("country.id"))) 
    .setResultTransformer(new AliasToBeanNestedResultTransformer(Address.class)); 

List<Address> result = criteria.list(); 

這個工程只是完美!

問題發生時,我只爲dataImport關係添加「別名」。即使沒有加入對dataImport.id投影到查詢

...createAlias("dataImport", "subdataImport")... 

,但只要我添加此別名返回一個空列表,這意味着則爲list.size()= 0。

我目前的猜測是,我不能把一個別名放在一個可爲空的屬性上。有沒有人知道解決方案可能是什麼?所以,當相關的實體不爲null時,我想要得到它的ID。而當我們沒有設置關係時,我希望它只是空的。

在此先感謝。

回答

0

愚蠢的我應該閱讀文檔並設置CriteriaSpecification.LEFT_JOIN。

...createAlias("dataImport", "subdataImport", CriteriaSpecification.LEFT_JOIN)...