英文:
Hibernate - How to load a Collection of ids for a ManyToMany relation without load the whole object with Lazy strategy
问题
我有一个JPA实体(Group),内部有一个集合(Device)(ManyToMany关系)。对于Group,有时我需要运行一个FindAll,其中包含完整加载的带有Devices集合的对象。另一次,我只需要运行一个FindAll,加载Group,但Devices集合只应该是一个id列表。我该如何做?我正在使用带有Spring Data和Hibernate的Spring Boot。
Device:
```java
@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<Device> devices;
...
}
GroupRepository:
public interface GroupRepository extends CrudRepository<Group, String> {
// 这将返回Group列表,以及与每个Group相关联的Devices列表
@Query("select g from Group g join fetch g.devices")
public List<Group> findAll();
// 这将返回Group列表,以及Devices id列表而不是完整的Device对象。
// 这个查询应该更快,因为Hibernate只需要检查内部表('group_device')以获取Devices id,
// 而不是在Device表中获取整个devices信息。
@Query("select distinct g from Group g left join g.devices")
public List<Group> findAllOnlyDevicesId();
}
英文:
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();
</details>
专注分享java语言的经验与见解,让所有开发者获益!
评论