【问题标题】:Adding parameters optionally to Spring Data JPA Native query可选地向 Spring Data JPA Native 查询添加参数
【发布时间】:2020-01-08 07:07:00
【问题描述】:

我正在使用 Spring Data JPA 和下面的原生查询

public interface ItemRepository extends JpaRepository<ItemEntity, Long> {

  @Query(value = "select * from items i where i.category = :itemCategory and i.item_code = :itemCode", nativeQuery = true)
  Page<ItemEntity> search(@Param("itemCategory") String itemCategory, @Param("itemCode") String itemCode, Pageable pageable);
}

现在,我的用例是

  1. itemCode 可用,只应返回该类别中带有该代码的项目。
  2. 但如果itemCode 不可用,则应退回该类别中的所有项目。

所以上述类别的问题是当itemCodeNULL 传递时,没有返回任何数据,因为它不匹配任何内容。而要求是它应该被忽略。

那么有没有一种方法可以选择向 Spring Data JPA 本机查询添加子句。我知道CriteriaQuery 是可能的,但我们可以为原生查询做类似的事情吗?

谢谢

【问题讨论】:

  • 看看使用 querydsl 扩展。这将允许您按类别、代码或类别和代码调用,而无需编写任何查询实现。

标签: spring spring-boot spring-data-jpa nativequery


【解决方案1】:

是的,原生查询也是可行的。 Very Good explanation here read this

#Approach1

@NamedQuery(name = "getUser", query = "select u from User u"
            + " where (:id is null or u.id = :id)"    
            + " And :username"

:itemCode is null or i.item_code = :itemCode

#Approach2

# UserDao.java 

  public User getUser(Long id, String usename) {
        String getUser = "select u from user u where u.id " + Dao.isNull(id) 
                       + " And u.username " + Dao.isNull(username);
        Query query = Dao.entityManager.createQuery(getUser);
    }

# Dao.java

   public static String isNull(Object field) {
        if (field != null) {
                if (field instanceof String) {
                    return " = " + "'" + field + "'";
                } else {
                    return " = " + field;
                }

            } else {
                return " is NULL ";
            }
    }

How to handle null value of number type in JPA named query

【讨论】:

    【解决方案2】:

    只需修改where条件

    i.item_code = :itemCode
    

    :itemCode is null or i.item_code = :itemCode
    

    【讨论】:

    • 这不是所要求的。
    • 对不起,为什么不呢?
    • 如果传递的参数为空,则忽略它,否则返回匹配。你的回答完全是另外一回事。本质上,如果参数为空,则不要添加条件 i.item_code = :itemCode。
    猜你喜欢
    • 2018-08-16
    • 2012-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多