Fetch join by JPQL in openjpa for many to many mapping

Fetch join by JPQL in openjpa for many to many mapping

我有一个设备和 device_group table,通过 device_group_mapping table 映射如下

CREATE TABLE device_group_mapping
(
  device_id character varying(64) NOT NULL,
  device_group_id bigint NOT NULL,
  CONSTRAINT "FK_device_group_mapping_device" FOREIGN KEY (device_id)
      REFERENCES device (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT "FK_device_group_mapping_device_group" FOREIGN KEY (device_group_id)
      REFERENCES device_group (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
)
WITH (
  OIDS=FALSE
);

openjpa的device和deviceGroup实体如下

@Entity
@Table(name = "device")
public class Device implements Serializable
{
    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "device_group_mapping", joinColumns =
    {@JoinColumn(name = "device_id", referencedColumnName = "id", nullable = false)}, inverseJoinColumns =
    {@JoinColumn(name = "device_group_id", referencedColumnName = "id", nullable = false)})
    private List<DeviceGroup>   deviceGroupCollection;  
}

@Entity
@Table(name = "device_group")
public class DeviceGroup implements Serializable
{
    @ManyToMany(mappedBy = "deviceGroupCollection", fetch = FetchType.EAGER)
    @OrderBy()
    private List<Device>    deviceCollection;
}

由于获取类型是惰性的,我必须按照下面的代码获取 deviceGroupCollection

@Override
@Transactional
public List<Device> findAllDevicesWithGroupMapping() throws Exception
{
    List<Device> list = new ArrayList<Device>();

    list = this.deviceDao.findAll();

    for (Device device : list)
    {
        device.setDeviceGroupCollection(device.getDeviceGroupCollection());
    }
    return list;
}

但是,当设备列表包含大量设备时,这将非常慢。

我想也许我可以通过 JPQL 和 fetch join device_group 找到设备实体,但不知道该怎么做。根据openjpa规范,它不支持on子句和嵌套fetch join。

我目前使用的openjpa如下

    <dependency>
        <groupId>org.apache.openjpa</groupId>
        <artifactId>openjpa-all</artifactId>
        <version>2.2.2</version>
    </dependency>

感谢任何帮助。

您可以像在任何其他关联上一样使用 Fetch Join 和 ManyToMany。您不需要任何 on 类,因为关联映射已经定义了两个实体如何相互链接:

select d from Device d
left join fetch d.deviceGroupCollection
where ...