Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data JPA native @Query with whole entity as named @Param

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.

like image 535
levant pied Avatar asked Jan 18 '26 08:01

levant pied


1 Answers

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]})")
like image 74
levant pied Avatar answered Jan 19 '26 22:01

levant pied



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!