首页 > 解决方案 > 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();

标签: javaspringhibernatejpaspring-data-jpa

解决方案


推荐阅读