带有空参数的 JPA NamedQuery

JPA NamedQuery with a null parameter

我有以下 NamedQuery:

@Entity
@NamedQuery(name = "query", query = "SELECT e FROM Entity e WHERE e.a = :a AND e.b = :b")
public class Entity {
    private String a;
    private String b;
    // Getters and Setters
}

我想将参数 a 设置为 someString 并将 b 设置为 null

这是使用 NamedQuery 的方法:

@PersistenceContext(unitName = "persistence-unit")
private EntityManager manager;

public List<Entity> getEntities(String a, String b) {
    TypedQuery<Entity> query = manager.createNamedQuery("query", Entity.class);
    query.setParamenter("a", a);
    query.setParamenter("b", b);
    return query.getResultList();
}

但是,当我调用 getEntities("someString", null); 时不起作用。

我猜是因为正确的是e.b IS NULL而这个方法是设置e.b = NULL.

我怎样才能让它发挥作用?

jpa/hibernate的老毛病了。不幸的是,不存在好的解决方案。在您的情况下,最好的解决方案是使用动态查询。

您可以按如下方式修改您的示例以实现某种有效的解决方法

@Entity
@NamedQueries ({
      @NamedQuery(name = "query", query = "SELECT e FROM Entity e WHERE e.a = :a AND e.b = :b"),
      @NamedQuery(name = "queryParamANull", query = "SELECT e FROM Entity e WHERE e.a IS NULL AND e.b = :b"),
      @NamedQuery(name = "queryParamBNull", query = "SELECT e FROM Entity e WHERE e.a = :a AND e.b IS NULL")
})
public class Entity {
    private String a;
    private String b;
    // Getters and Setters
}

因此,您可以按如下方式查询数据(注意假设只有ab 每个方法可以为 null call/query):

@PersistenceContext(unitName = "persistence-unit")
private EntityManager manager;

public List<Entity> getEntities(String a, String b) {
    TypedQuery<Entity> query;
    if(a==null) // we got no value for a
    {
        query = manager.createNamedQuery("queryParamANull", Entity.class);
        query.setParamenter("b", b);
    }
    else if(b==null) // we got no value for b
    {
        query = manager.createNamedQuery("queryParamBNull", Entity.class);
        query.setParamenter("a", a);
    }
    else // default case
    {
        query = manager.createNamedQuery("query", Entity.class);
        query.setParamenter("a", a);
        query.setParamenter("b", b);
    }
    return query.getResultList();
}