简体   繁体   中英

jpql variable that can be null

I have an jpql query inside a JpaRepository like this:

@Query("select l from LogEntity l where l.codePackage = :codePackage and l.codeFile = :codeFile order by l.id desc")
public Page<LogEntity> findSimilarAngularLog (@Param("codePackage") String codePackage, @Param("codeFile") String codeFile, Pageable pageRequest);

The variable codePackage and codeFile can be NULL. But hibernate is always making something like

... where l.codePackage=? and l.codeFile=? ...

out of it. So if one or both of them are NULL, then there is l.codeFile=NULL and not l.codeFile IS NULL . And then he does not find anything at all.
If I copy the hibernate generated sql string to my MySQL console and change the =NULL to IS NULL , he will find everything.

So how do I change the behavior of hibernate jpa, so that in my @Query String the NULL will be treated correctly.

thanks a lot and greetings

WHERE ((:param is null and t.field is null) or t.field = :param)
@Query("select l from LogEntity l where ((:codePackage is null and l.codePackage is null) or l.codePackage = :codePackage ) and ((:codeFile is null and l.codeFile is null) or l.codeFile = :codeFile ) order by l.id desc")

You can use the below query for that:

@Query("select l from LogEntity l where ((:codePackage is null and l.codePackage is null) or l.codePackage = :codePackage) and ((:codeFile is null and l.codeFile is null) or l.codeFile = :codeFile) order by l.id desc")

But wouldn't that be a good idea to make hql through the logic rather than using it like the named queries?

A better logic would be to use an if condition, like,

if(codePackage == null) {
    query += " l.codePackage is null ";
}
else {
    query += " l.codePackage = :codePackage ";
}
***code***
//query execution code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM