【问题标题】:JPA @Query with Complex nullable object具有复杂可为空对象的 JPA @Query
【发布时间】:2019-03-22 06:37:48
【问题描述】:

我正在构建一个带有 getAll 查询的存储库,该查询使用复杂类型参数进行过滤,例如:

@Query("""
    SELECT c FROM City c
    WHERE :filter IS NULL OR c.code LIKE %:#{#filter.code}%
    """)
fun getAllCitiesFiltered(@Param("filter") filter: MyFilter?) : List<City>

MyFilter 类是一个简单的 POJO:

class MyFilter {
    var code: String? = null
    var description: String? = null
}

在我的代码中的某个时刻,我调用了getAllCitiesFiltered(filter),而这个filter 可能为空,或者它的属性之一设置为空。我有两个问题:

  • 如何处理filter 可以为空的事实?现在的方式(如上),每当将null 值传递给它时,我都会得到一个异常EL1007E: Property or field 'code' cannot be found on null
  • 在 HQL 中是否有一种不那么丑陋的方式来处理属性 codedescription 可能为 null 并且当它们为 null 时我不想被它们过滤的事实?我现在想到的唯一方法是做... WHERE filter.code IS NULL or filter.code LIKE %c.code%之类的事情

我是 JPA 的新手,我不确定使用 @Query 是否是这里的最佳方法。我也愿意接受改变这一点的建议。

谢谢!

根据 Alan Hay 的建议进行编辑

我正在使用 QueryDSL,并且来自 C#/LINQ 背景,发现它很棒。 “问题”是我正在做这样的事情:

val city = QCity.city
var query = JPAQuery<City>(entityManager).from(city)

if (filter?.code != null)
    query = query.where(city.code.eq("BH"))

if (filter?.description != null)
    query = query.where(city.description.eq("Belo Horizonte"))

除了切换和 if/else'ing 之外,还有更好的写法吗?

谢谢!

【问题讨论】:

标签: java jpa kotlin spring-data-jpa spring-data


【解决方案1】:

最好的方法是使用接口默认方法:

interface CityJpaRepository : JpaRepository<City, Int> {
  fun findByCodeLike(code: String) : List<City>

  fun findByFilter(filter: MyFilter?) : List<City> {
    return filter?.code?.let { findByCodeLike(it.code) } ?: findAll()
  }
}

【讨论】:

    猜你喜欢
    • 2021-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-14
    • 1970-01-01
    • 2018-10-06
    • 2013-03-15
    • 2019-04-07
    相关资源
    最近更新 更多