How to not fetch associated child relation

23 views Asked by At

I have this constellation:

public class Users {
    private final @Id
    @With
    long id;

    private final String userName;

    private final String firstName;

    private final String lastName;

    private final LocalDateTime created;

    @With
    @MappedCollection(idColumn = "users_id")
    private final Set<Privileges> privileges;
}

I have this query to fetch all users:

    @Query("select u.id, u.userName, u.firstName, u.lastName from users u order by u.username")
    List<Users> findsAllOrderedByUserName();

When i set the debug level for spring data jdbc (to get the queries fired to the db), i can see that there are lots of queries to get the Set<Privileges> to every user.

Is there a way to tell Spring Data JDBC to not fetch this Set<> automatically?

1

There are 1 answers

0
Thomas Lang On

I have just figured it out.

You need to provide a DTO (Data Transfer Object) or a record as return type for the Query - not the entity with the Set<>.

@Query("select u.id, u.userName, u.firstName, u.lastName, 0 as privilegeId, 0 as role from users u order by u.username")
    List<UsersDto> findsAllOrderedByUserName();

The DTO:

public record UsersDto(long id, @NotNull @NotEmpty String userName, @NotNull @NotEmpty String firstName,
                       @NotNull @NotEmpty String lastName, long privilegeId, int role)