Mr. Mak
Mr. Mak

Reputation: 867

Hibernate Criteria, createAlias() If Alias is Null

In the code below.. There are two Alias as Entity Object Reference. Sometimes "caseStage" as stage can be null in Database. When "caseStage" is null I want stage.name value as an empty String or something customized like "---" etc.

session.createCriteria(CaseMasterPO.class)
       .createAlias("branch", "br")     // BranchPO.class
       .createAlias("caseStage", "stage") // CaseStagePO.class
       .setProjection(Projections.projectionList()
          .add(Projections.property("caseCode"))
          .add(Projections.property("br.zoneCode"))
          .add(Projections.property("stage.name")) // Problem, when stage == null
       )
       .add(Restrictions.eq("caseCode", caseCode)).uniqueResult();

Upvotes: 2

Views: 2670

Answers (2)

IgniteCoders
IgniteCoders

Reputation: 4980

@Koti Eswar answer is right, but it's deprecated now.

It's should be done like this:

        join('branch', JoinType.LEFT)
        createAlias('branch', 'br')

Tested in Grails 3.3.5

Upvotes: 2

Koti Eswar
Koti Eswar

Reputation: 86

Set the CriteriaSpecification.LEFT_JOIN to alias function

.createAlias("branch", "br" , CriteriaSpecification.LEFT_JOIN) .createAlias("caseStage", "stage", CriteriaSpecification.LEFT_JOIN)

Upvotes: 7

Related Questions