Say I have two entities:
class User {
@Id private int id;
private String name;
private int addressId;
}
class Address {
@Id private int id;
private String street;
}
Is it possible to do this:
interface UserRepository extends CrudRepository<User, Integer> {
@Query(nativeQuery=true,
value=
"select * from user "
+ "inner join address a on a.id = u.addressId "
+ "where a.street = :address.street")
List<User> findByAddress(@Param("address") Address address);
}
That is: accept an entity (Address in this case) as the parameter, but reference one of its properties (Address.street in this case) in the native query?
For various reasons, I cannot use "normal" @ManyToMany and JPA queries for these two entities.
Found an answer here:
https://spring.io/blog/2014/07/15/spel-support-in-spring-data-jpa-query-definitions
This can be used:
+ "where a.street = :#{#address.street}")
Bonus - for a.street in(...), use collection projections:
https://docs.spring.io/spring/docs/4.3.10.RELEASE/spring-framework-reference/html/expressions.html#expressions-collection-projection
That is:
+ "where a.street in(:#{#address.![street]})")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With