3

When doing querys you can do this syntax:

@Query(value = "SELECT v from DBTABLE v WHERE v.param1 = param1 AND v.param2 = param2")
List<Result> search(@Param("param1") String param1, @Param("param2") String param2)

What if I had more then 2 parameters. Lets say I had 20 parameters, is there a way to give an object instead and refer to the object properties instead? What I mean is this:

Pseudocode:

@Query(value = "SELECT v from DBTABLE v WHERE v.param1 = object.param1 AND v.param2 = object.param2")
List<Result> search(@Param("Object") SomeCustomObject object)
3
  • I guess, there's nothing on that link about my question. Commented Jul 27, 2023 at 8:57
  • 1
    I see, I thought it would be implied, but I found that is quite similar to what you are looking for. Does this work for you? stackoverflow.com/a/28993810/16034206 Commented Jul 27, 2023 at 8:59
  • That's the exact thing I was looking for, thank you. You can post an answer and I'll accept it. Commented Jul 27, 2023 at 11:24

1 Answer 1

5

Spring Data JPA has SpEL support that provides access to the query method arguments. This allows you to either simply bind the parameter as is or perform additional operations before binding.

This lets you write queries such as:

@Query("select u from User u where u.age = ?#{[0]}")
List<User> findUsersByAge(int age);

@Query("select u from User u where u.firstname = :#{#customer.firstname}")
List<User> findUsersByCustomersFirstname(@Param("customer") Customer customer);

For more details, see also

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.