2

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();
Mr. Mak
  • 837
  • 1
  • 11
  • 25
  • I usually use coalesce(stage.name, '---') in HQL, so is there any mechanism for Criteria Query ? – Mr. Mak Nov 21 '16 at 07:30
  • what is the problem you are facing .. please explain that ?? – Zulfi Nov 21 '16 at 08:13
  • How you display your objects on the screen shouldn't be decided and specified in a database query. Modify your presentation-layer code to display whatever you want in case the value is null. – JB Nizet Nov 21 '16 at 09:22
  • Can't you just use Projections.sqlProjection instead? – StanislavL Nov 21 '16 at 09:24
  • @Zulfi, In the above code there is a `Projections` with property name `stage.name`. I do not get the rows when`stage` is `null`. in database. – Mr. Mak Nov 22 '16 at 08:47
  • can you also post your entity classes – Zulfi Nov 22 '16 at 08:54

2 Answers2

7

Set the CriteriaSpecification.LEFT_JOIN to alias function

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

Koti Eswar
  • 86
  • 1
  • 5
2

@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

IgniteCoders
  • 4,834
  • 3
  • 44
  • 62