Spring data JPA query with parameter properties

后端 未结 9 1143
既然无缘
既然无缘 2020-11-29 00:20

What is the simplest way of declaring a Spring data JPA query that uses properties of an input parameter as query parameters?

For example, suppose I have an entity c

相关标签:
9条回答
  • 2020-11-29 01:13

    You could also solve it with an interface default method:

     @Query(select p from Person p where p.forename = :forename and p.surname = :surname)
    User findByForenameAndSurname(@Param("surname") String lastname,
                             @Param("forename") String firstname);
    
    default User findByName(Name name) {
      return findByForenameAndSurname(name.getLastname(), name.getFirstname());
    }
    

    Of course you'd still have the actual repository function publicly visible...

    0 讨论(0)
  • 2020-11-29 01:18

    Define the query method with signatures as follows.

    @Query(select p from Person p where p.forename = :forename and p.surname = :surname)
    User findByForenameAndSurname(@Param("surname") String lastname,
                                 @Param("forename") String firstname);
    }
    

    For further details, check the Spring Data JPA reference

    0 讨论(0)
  • 2020-11-29 01:18

    Are you working with a @Service too? Because if you are, then you can @Autowired your PersonRepository to the @Service and then in the service just invoke the Name class and use the form that @CuriosMind... proposed:

    @Query(select p from Person p where p.forename = :forename and p.surname = :surname)
    User findByForenameAndSurname(@Param("surname") String lastname,
                             @Param("forename") String firstname);
    }
    

    and when invoking the method from the repository in the service, you can then pass those parameters.

    0 讨论(0)
提交回复
热议问题