带有null参数的JPA NamedQuery

时间:2015-03-05 20:56:38

标签: postgresql parameters named-query

我有以下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

我怎样才能使它有效?

2 个答案:

答案 0 :(得分:2)

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

@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为空/查询):

@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();
}

答案 1 :(得分:0)

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