Spring Data JPA - Where子句中的很多列
问题描述:
我需要确定一个实体是否已被持久化。不幸的是,我没有这个id,但是如果实体的其他六个字段的值匹配一个持久化实体,我可以确定该实体已经存在。我使用Spring JPA存储库和知道我可以做到以下几点:Spring Data JPA - Where子句中的很多列
Test findByField1AndField2And...(String field1, String field2,...)
有没有办法做同样的东西:如果你使用Spring数据JPA 1.7
@Query("SELECT t "
+ "FROM Test t "
+ "WHERE "
+ "t.field1 = :testWithSomeFieldsPopulated.field1 and "
+ "t.field2 = :testWithSomeFieldsPopulated.field2 and ...")
Test findByTest(@Param("testWithSomeFieldsPopulated") Test testWithSomeFieldsPopulated)
答
。 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)
相似的答案[这里](http://stackoverflow.com/a/28993810/2646526)。 – heenenee
谢谢。如果't.fieldx为空且testWithSomeFieldsPopulated.fieldx为空',我还需要从Test返回一行。你知道是否有某种方法可以通过'@ Query'或其他方式来设置ansi nulls关闭(SQL Server),或者用其他方式来完成这个任务,除了写'(t.field1 =:#{#testWithSomeFieldsPopulated.field1}或者(t .field为空,并且:#testWithSomeFieldsPopulated.field1为空))'为每个字段?我知道这是一个后续问题。你的回答上面回答了我原来的问题,我打算将它标记为这样。 – James
我通常使用[COALESCE](https://msdn.microsoft.com/en-us/library/ms190349.aspx)为这种事情的标志值。 – heenenee