开发者

How to query a column which value is null in JPA?

开发者 https://www.devze.com 2023-03-12 04:05 出处:网络
I am using JPA namedQuery to select data from DB. @NamedQuery(name = \"Concept.findByRefTableNull\", query = \"SELECT c FROM Concept c WHERE c.conceptName = :conceptName and c.refTable = :refTable\

I am using JPA namedQuery to select data from DB.

 @NamedQuery(name = "Concept.findByRefTableNull", query = "SELECT c FROM Concept c WHERE c.conceptName = :conceptName and c.refTable = :refTable"),

///
 List<Concept> attributeList 
                = em.createNamedQuery("Concept.findByRefTableNull")
                .setParameter("conceptName", "student").
                setParameter("refTable"开发者_StackOverflow, null).
                getResultList();

        System.out.println(attributeList.size()); //return 0

The List size is 0, but I am sure it should have records. The reason is the refTable. How to query a column which value is null in JPA ?

Thanks.


Just change your query to

 @NamedQuery(name = "Concept.findByRefTableNull", query = "SELECT c FROM Concept c WHERE c.conceptName = :conceptName and c.refTable IS NULL"),


I'm not sure if this is a Spring Data JPA feature only but I just write a method in the repository interface of the form findByFieldName(Type field) where fieldName is the name of the column I need to do a null check on. I then use this method and pass null as a parameter.


You can use Criteri Api , like this :

private Specification<Object> nullData(String field) {
    return (root, query, cb) ->
            cb.isNull(cb.lower(root.get(field)));
}


i would avoid Queries altogether - it pretty much negates the sense of persistence-abstraction. Create dynamic queries via the Criteria API instead, this will ensure portability AND you will be able to switch databases to some extent without much hassle

0

精彩评论

暂无评论...
验证码 换一张
取 消