У меня есть сущность JPA (группа) с коллекцией (устройством) внутри нее (отношение ManyToMany). Для группы иногда мне нужно запустить FindAll с полным объектом с полностью загруженной коллекцией устройств. В другой раз мне просто нужно запустить FindAll, который загружает Group, но коллекция Devices должна быть просто списком идентификаторов. Как я могу это сделать? Я использую Spring Boot с Spring Data и Hibernate.
Устройство:
@Entity
public class Device {
@Id
@Access(AccessType.PROPERTY)
private String id;
private String name;
...
}
Группа:
@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();