2015-09-06 26 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