Search code examples
javahibernatealiashibernate-criteriacriteriaquery

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();

Solution

  • Set the CriteriaSpecification.LEFT_JOIN to alias function

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