3

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.

1 Answer 1

9

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]})")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.