2016-01-22 31 views
9

我需要確定一個實體是否已被持久化。不幸的是,我沒有這個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) 

回答

5

。 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) 
+0

相似的答案[這裏](http://stackoverflow.com/a/28993810/2646526)。 – heenenee

+0

謝謝。如果't.fieldx爲空且testWithSomeFieldsPopulated.fieldx爲空',我還需要從Test返回一行。你知道是否有某種方法可以通過'@ Query'或其他方式來設置ansi nulls關閉(SQL Server),或者用其他方式來完成這個任務,除了寫'(t.field1 =:#{#testWithSomeFieldsPopulated.field1}或者(t .field爲空,並且:#testWithSomeFieldsPopulated.field1爲空))'爲每個字段?我知道這是一個後續問題。你的回答上面回答了我原來的問題,我打算將它標記爲這樣。 – James

+1

我通常使用[COALESCE](https://msdn.microsoft.com/en-us/library/ms190349.aspx)爲這種事情的標誌值。 – heenenee