I have a JPA entity (Group) with a collection (Device) inside of it (a ManyToMany relation). For the Group, sometimes I need to run a FindAll with the full object with the collection of Devices fully loaded. Another time I just need to run a FindAll that loads Group, but the collection of Devices should be just a list of ids. How can I do that? I am using Spring Boot with Spring Data and Hibernate.
Device:
@Entity
public class Device {
@Id
@Access(AccessType.PROPERTY)
private String id;
private String name;
...
}
Group:
@Entity
public class Group {
@Id
private String id;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(
name = "group_device",
joinColumns = @JoinColumn(name = "group_id"),
inverseJoinColumns = @JoinColumn(name = "device_id"))
private Set<Devices> devices;
...
}
GroupRepository:
public interface ShortenRepository extends CrudRepository<Shorten, String> {
// This return the list of groups and also the list of Devices related to each one
@Query("select g from Group g join Device d")
public List<Group> findAll();
// This return the list of groups and also the list of Devices ids instead of the full Device object.
// This query should be faster because Hibernate just needs to check the inner table ('group_device') to fetch the Devices ids
// instead of fetching the whole devices info in the Device table.
@Query("select g from Group g join Device d")
public List<Group> findAllOnlyDevicesId();