2012-01-27 15 views
3

所以我有:讀取實體A時從實體B讀取的值(左連接上非PK柱) - JPA 2.0

@Entity 
public class Entity { 

    @EmbeddedId 
    private MyId id; 

    // not a part of Entity but a part of OtherEntity 
    private String lookedUpValue; 

} 

public class MyId { 
    private String firstField; 
    private String secondField; 
} 

表看起來像:

ENTITY 
    FIRSTFIELD (PK) 
    SECONDFIELD (PK) 
    // etc. 

public class OtherEntity { 
    private String firstField; 
    private String value; 
} 

表看起來像:

OTHERENTITY 
    VALUE (PK) 
    FIRSTFIELD 
    //etc. 
} 

當我讀到實體我希望這是一個LEFT JOIN來填充其lookedUpValue場,其中Entity.id.firstField = OtherEntity.firstField即SQL它禾ULD是:

Select ENTITY.FIRSTFIELD, ENTITY.SECONDFIELD, OTHERENTITY.VALUE 
from ENTITY 
left join OTHERENTITY 
ON ENTITY.FIRSTFIELD = OTHERENTITY.FIRSTFIELD 

所以實體實例將與所有這些領域得到填充。

這是可能的,或者你推薦另一種方法?將OtherEntity作爲每個實體上的字段讀取也可以工作 - 但由於MyId沒有映射到OtherEntity,所以我沒有看到如何實現這一點。非常感謝。

回答

0

您可能想在這裏使用JPQL Constructor Expressions

基本上,您創建了一個DTO,包含您需要的所有字段並在查詢中使用它的構造函數(與NEW)。

1

一種使用JoinColumn註釋引用Entity中的OtherEntity的方法,下面的代碼位於Entity中。

@OneToOne(optional="true") 
@JoinColumn(name="FIRSTFIELD",referencedColumnName="FIRSTFIELD") 
OtherEntity otherEntity;