Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data JPA - Many columns in where clause

I need to determine if an entity has already been persisted. Unfortuantely, I do not have the id, but I can determine that the entity is already persisted if the value of six other fields of the entity match a persisted entity. I'm using Spring JPA repositories and know that I can do the following:

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

Is there a way to do something similar to:

 @Query("SELECT t "
           + "FROM Test t "
           + "WHERE "
           + "t.field1 = :testWithSomeFieldsPopulated.field1 and "
           + "t.field2 = :testWithSomeFieldsPopulated.field2 and ..." ) 
Test findByTest(@Param("testWithSomeFieldsPopulated") Test testWithSomeFieldsPopulated)
like image 538
James Avatar asked Jan 22 '16 16:01

James


1 Answers

If you're using Spring Data JPA 1.7.0 or above, then you can accomplish this by using SpEL in your @Query definition. So something like:

@Query("SELECT t "
           + "FROM Test t "
           + "WHERE "
           + "t.field1 = :#{#testWithSomeFieldsPopulated.field1} and "
           + "t.field2 = :#{#testWithSomeFieldsPopulated.field2} and ..." ) 
Test findByTest(@Param("testWithSomeFieldsPopulated") Test testWithSomeFieldsPopulated)
like image 137
heenenee Avatar answered Oct 01 '22 13:10

heenenee