4

I created a query method using a Reference from another Aggregate.

@Getter
@AllArgsConstructor(access = AccessLevel.PRIVATE, onConstructor_=@PersistenceConstructor)
public static class Book {

    public static Book of(Author author) {
        return new Book(null, AggregateReference.to(author.id));
    }

    @Id
    private Long id;

    private AggregateReference<Author, Long>  authorId;
}
interface BookRepository extends CrudRepository<Book, Long> {

    List<Book> findBooksByAuthorId(Long  authorId);
}

But I got the following exception:

    Caused by: java.lang.IllegalArgumentException: Cannot query by reference: authorId
    at 

I have checked the source below. But I don't understand why it throws an exception.

org.springframework.data.jdbc.repository.query.JdbcQueryCreator.validateProperty(JdbcQueryCreator.java:146)
        private static void validateProperty(PersistentPropertyPathExtension path) {
         .....

        if (path.getRequiredPersistentPropertyPath().getLeafProperty().isReference()) {
            throw new IllegalArgumentException(
                    String.format("Cannot query by reference: %s", path.getRequiredPersistentPropertyPath().toDotPath()));
        }
    }

Why can't I create a query method on a Reference?

The source for your reference is here. https://github.com/yangwansu/try-spring-data-jdbc/blob/main/src/test/java/masil/example/springdata/jdbc/ch9_7/QueryToAggregateReferenceTest.java

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
Wansu yang
  • 66
  • 4

1 Answers1

0

For anybody coming to this at a later time:

This was a limitation of Spring Data JDBC. Thanks for finding it.

It is now properly implemented. The first version with the fix included is the 2.3 M1 release.

See the issue created by Wansu yang for details.

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348