2015-09-06 77 views
0

我具有由device_group_mapping表的设备和device_group表,映射如下获取由JPQL在OpenJPA加入用于多对多映射

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的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加入device_group,但不知道该怎么做。根据openjpa规范,它不支持on子句,也嵌套fetch连接。

OpenJPA的我目前使用如下

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

任何帮助表示赞赏。

回答

1

您可以像使用其他任何关联一样使用获取连接ManyToMany。您不需要任何on类,因为关联映射已经定义了两个实体之间如何链接:

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

谢谢JB。这个答案解决了我的问题。 – Bruce