繁体   English   中英

JPQL在openjpa中获取多对多映射的联接

[英]Fetch join by JPQL in openjpa for many to many mapping

我有一个device和device_group表,通过device_group_mapping表进行映射,如下所示

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来找到设备实体,并通过提取加入device_group,但不知道该怎么做。 根据openjpa规范,它不支持on子句,也不支持嵌套的访存联接。

我目前使用的openjpa如下

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

任何帮助表示赞赏。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM