【问题标题】:Spring Data JPA - Many columns in where clauseSpring Data JPA - where 子句中的许多列
【发布时间】:2016-04-29 08:37:27
【问题描述】:

我需要确定一个实体是否已经被持久化。不幸的是,我没有 id,但是如果实体的其他六个字段的值与持久化实体匹配,我可以确定该实体已经持久化。我正在使用 Spring JPA 存储库,并且知道我可以执行以下操作:

Test findByField1AndField2And...(String field1, String field2,...)

有没有办法做类似的事情:

 @Query("SELECT t "
           + "FROM Test t "
           + "WHERE "
           + "t.field1 = :testWithSomeFieldsPopulated.field1 and "
           + "t.field2 = :testWithSomeFieldsPopulated.field2 and ..." ) 
Test findByTest(@Param("testWithSomeFieldsPopulated") Test testWithSomeFieldsPopulated)

【问题讨论】:

    标签: spring-data-jpa


    【解决方案1】:

    如果您使用的是 Spring Data JPA 1.7.0 或更高版本,则可以通过 using SpEL in your @Query definition 完成此操作。所以像:

    @Query("SELECT t "
               + "FROM Test t "
               + "WHERE "
               + "t.field1 = :#{#testWithSomeFieldsPopulated.field1} and "
               + "t.field2 = :#{#testWithSomeFieldsPopulated.field2} and ..." ) 
    Test findByTest(@Param("testWithSomeFieldsPopulated") Test testWithSomeFieldsPopulated)
    

    【讨论】:

    • 谢谢。如果t.fieldx is null and testWithSomeFieldsPopulated.fieldx is null,我还需要从Test 返回一行。您是否知道是否有某种方法可以在@Query 中将 ansi 空值设置为关闭(SQL Server),或者除了为每个字段编写(t.field1 = :#{#testWithSomeFieldsPopulated.field1} or (t.field is null and :#testWithSomeFieldsPopulated.field1 is null)) 之外的其他方法来完成此操作吗?我知道这是一个后续问题。您上面的回答回答了我最初的问题,我打算将其标记为这样。
    • 我通常使用COALESCE 和标志值来处理这类事情。
    猜你喜欢
    • 2021-12-24
    • 2015-09-20
    • 2017-01-18
    • 2016-11-26
    • 2016-11-15
    • 2020-07-10
    • 1970-01-01
    • 2012-12-16
    • 1970-01-01
    相关资源
    最近更新 更多