Search code examples
javaspring-dataspring-elspring-data-jdbc

Can Spring Data JDBC use object properties as query parameters?


Currently I use the following code for a custom SQL statement in a Spring Data JDBC Repository interface:

default void upsert(LoanRecord r) {
    upsert(r.getId(), r.getUcdpDocumentFileId(), r.getFreSellerNo(),
            r.getFreDeliverySellerNo(), r.getLenderLoanNo(), r.getFreLpKey());
}

@Modifying
@Query("""
    INSERT INTO loan (id, ucdp_document_file_id, lender_loan_no, fre_seller_no, fre_delivery_seller_no, fre_lp_key)
        values (:id, :ucdpDocumentFileId, :lenderLoanNo, :freSellerNo, :freDeliverySellerNo, :freLpKey)
    ON CONFLICT (ucdp_document_file_id) DO UPDATE SET
        lender_loan_no = EXCLUDED.lender_loan_no,
        fre_seller_no = EXCLUDED.fre_seller_no,
        fre_delivery_seller_no = EXCLUDED.fre_delivery_seller_no,
        fre_lp_key = EXCLUDED.fre_lp_key""")
void upsert(UUID id, String ucdpDocumentFileId, String freSellerNo,
        String freDeliverySellerNo, String lenderLoanNo, String freLpKey);

The actual statement doesn't really matter, but as you can see, there's a wrapper method that unpacks the object so I can use simple parameters in the second method. Is there some way to refer to object properties in the query (like with MyBatis) so we can get rid of the wrapper method?

For reference, my spring-data-jdbc version is 2.4.2.


Solution

  • This is possible with the latest milestone release of Spring Data JDBC(3.0.0-RC1! It is probably the main use case behind SpEL support. With it you can now use constructs like this:

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

    Just as you can for a long time in Spring Data JPA.