简体   繁体   English

如何在JPA中查询哪个值为null的列?

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

I am using JPA namedQuery to select data from DB. 我正在使用JPA namedQuery从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", null).
                getResultList();

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

The List size is 0, but I am sure it should have records. 列表大小为0,但我确信它应该有记录。 The reason is the refTable. 原因是refTable。 How to query a column which value is null in JPA ? 如何在JPA中查询哪个值为null的列?

Thanks. 谢谢。

只需将您的查询更改为

 @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. 我不确定这是否只是一个Spring Data JPA功能,但我只是在findByFieldName(Type字段)形式的存储库接口中编写一个方法,其中fieldName是我需要进行空检查的列的名称。 I then use this method and pass null as a parameter. 然后我使用此方法并将null作为参数传递。

You can use Criteri Api , like this : 您可以使用Criteri Api,如下所示:

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 通过Criteria API创建动态查询,这将确保可移植性并且您将能够在某种程度上切换数据库而不会有太多麻烦

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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