Search code examples
javaspringspring-data-jpajpqlprojection

JPQL -- null to boolean?


Let's say I have an Entity

@Entity
@Table(name = "foos")
class Foo{
   @Id
   @Generatedvalue(strategy = IDENTITY)
   private Long id;

   @ManyToOne
   @JoinColumn(name = "bar_id")
   private Bar bar;

   ...
}

and a Projection that should give me an id and a boolean telling me whether or not the instance has a Bar:

interface FooProjection{
    String getId();
    Boolean hasBar();
}

How do you write the JPQL query?

I did try

@Query(
    "SELECT"
    "   f.id,"
    "   (f.bar IS NOT NULL) AS bar"
    " FROM Foo f"
)
List<FooProjection> findProjections();

Which got me an org.eclipse.persistence.exceptions.JPQLException with the very helpful error message

The expression is invalid, which means it does not follow the JPQL grammar.

How DO you write this query?


Solution

  • I don't know if you should be running this query as you have it, but one fix for the syntax would be to use a CASE expression:

    @Query(
        "SELECT"
        "   f.id,"
        "   CASE WHEN f.bar IS NOT NULL THEN TRUE ELSE FALSE END AS bar"
        " FROM Foo f"
    )
    List<FooProjection> findProjections();