java - Hibernate - 如何在不使用惰性策略加载整个对象的情况下为多对多关系加载 id 集合
问题描述
我有一个 JPA 实体(组),里面有一个集合(设备)(多对多关系)。对于组,有时我需要运行带有完整对象的 FindAll,并且设备集合已完全加载。还有一次我只需要运行一个加载 Group 的 FindAll,但 Devices 的集合应该只是一个 id 列表。我怎样才能做到这一点?我正在将 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;
...
}
组库:
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();
解决方案
推荐阅读
- javascript - 在 css 中使用 url() 时如何设置图像的宽度和高度
- spring - Spring Data - 带有过滤的自定义 DTO 查询
- android - 具有“状态”设计模式的 Android Camera2 API
- apache-kafka - 当 3 个代理中的 1 个出现故障时,Kafka 无法获得偏移量
- wordpress - 如何将订购的 3D 模型变成具有变化的 woocommerce 产品?
- google-analytics - 为电子商务项目的动态 URL 设置目标
- python - 在 scikit learn 中预测多个值作为模型结果
- android - 当我想从 Firebase 获取数据时,为什么应用程序会关闭?
- tcp - 进程和 TCPSocket 在水晶中没有正确关闭
- pandas - 如何将ndarray转换为pandas DataFrame