JPA / eclipselink:在一个查询中连接获取注释@OneToOne的所有子项

时间:2016-08-19 06:08:06

标签: jpa orm eclipselink jpa-2.1

我们尝试在一个查询中连接获取数据,但只加入了LocationAddress连接。对于LocationGeodata,jpa始终生成第二个查询。不尊重LocationAddress中的@ JoinFetch-Annotation。

给出以下模型和单向注释:

位置-----&LT 1为卤素; LocationAddress -----&LT 1为卤素; LocationGeodata

每个位置都有一个地址,每个地址都引用一个全局地理数据表。还授予我们在任何表中都没有空值。

映射:

@Entity
public class Location {

   @OneToOne(cascade=CascadeType.ALL)
   @JoinFetch(JoinFetchType.INNER)  
   private LocationAddress locationAddress;
}

@Entity
public class LocationAddress {

    @OneToOne   
    @JoinFetch(JoinFetchType.INNER)
    private LocationGeodata locationGeoData;    
}

按ID分配位置会产生两个查询:

@NamedQuery(
        name="Location.getById",              
        query="SELECT l FROM Location l WHERE l.id = :id"
)

//produces same sql-result as above query
@NamedQuery(
        name="Location.getById",              
        query="SELECT l, lg FROM Location l
               JOIN FETCH l.locationAddress a
               JOIN FETCH a.locatonGeodata lg
               WHERE l.id = :id"
)

SELECT t1.ID, t1.DESCRIPTION, t1.LOCATIONADDRESS_ID, t2.STREET, 
       t2.HOUSENUMBER, t2.LOCATIONGEODATA_ID FROM LOCATION t1 
INNER JOIN LOCATIONADDRESS t2 
WHERE t1.LOCATIONADDRESS_ID = t2.ID AND t1.ID = ?


SELECT ID, ADMINCODE1, ADMINNAME1, COUNTRYCODE, LAT, LONG 
FROM LOCATIONGEODATA WHERE (ID = ?)

我们如何将第二个查询合并到第一个查询?谢谢你的建议!

相关表定义:

位置
locationAdress_ID

LocationAddress
loationGeoData_ID

1 个答案:

答案 0 :(得分:0)

奇怪的是,我花了好几天尝试错误并找到答案,在这里发布问题后,找到了解决方案。添加查询提示会生成所需的查询:

@NamedQuery(
    name="Location.getById",              
    query="SELECT l FROM Location l WHERE l.id = :id",
    hints= {
        @QueryHint(name = "eclipselink.join-fetch", 
                   value = "l.locationAddress.locationGeodata")               
    }

感谢

http://java-persistence-performance.blogspot.de/2010/08/batch-fetching-optimizing-object-graph.html

主题是指"嵌套连接提取查询提示"