I've been trying to use Spring Data JPA Projections. Also using @Value annotation to concat some properties of some referenced projections.
The problem occurs when one of the referenced projections return 'null' because that particular column is null in the DB. Is there any way to scoot around this issue? i.e., if any of the referenced projections are null then is it possible to not use that projection and still use values of other projections?
Sample code:
public interface InitialProjection{
String getName();
ReferencedProjection1 getRp1();
ReferencedProjection2 getRp2();
@Value("#{target.name + ' - ' + target.rp1.name + ' - ' + target.rp2.name}")
String getDetail();
}
public interface ReferencedProjection1 {
String getName();
}
public interface ReferencedProjection2 {
String getName();
}
Also, since I'm having to use @Query annotated methods it seems to need to specify LEFT JOIN for every mapped entity. Is it required or is there a way to not having to specify all the aliases?
Sample code:
@Query("SELECT entity.name AS name, "
+ "ljrp1 AS rp1, "
+ "ljrp2 AS rp2 "
+ "FROM Entity entity "
+ "LEFT JOIN entity.rp1 ljrp1 "
+ "LEFT JOIN entity.rp2 ljrp2 "
+ "WHERE entity.isDeleted = 0 ORDER BY entity.name ASC")
List<InitialProjection> fetchAllActiveEntities();
Solution for the first part: As explained in the accepted answer, the mapped projections can be checked for null using Spring Expression Language. They are to be included in parantheses as given below.
@Value("#{target.name + ' - ' + (target.rp1 != null ? target.rp1.name : '' )+ ' - ' + (target.rp2 != null ? target.rp2.name : '')}")
If I understand your question correctly you are asking about null checks in Spring Expression Language.
So you could do:
@Value("#{target.name + ' - ' + (target.rp1 != null ? target.rp1.name : '') + ' - ' + (target.rp2 != null ? target.rp2.name : '')}")
And about outer join (in your case left join): Yes you need that to allow null vaules in the relationships.