2013-02-08 197 views
4

這些是我的(略)實體:休眠:選擇在一對多關係

@Entity 
public class User { 

    @OneToMany(fetch=FetchType.LAZY) 
    @JoinTable(name="user_items",[email protected](name="user_id"),[email protected](name="useritem_id")) 
    private Set<UserItem> items = Sets.newHashSet(); 

} 


@Entity 
@Inheritance(strategy=InheritanceType.JOINED) 
public class UserItem { 

    @Id 
    @Type(type=EntityConstants.TYPE_UUID) 
    @Column(columnDefinition=EntityConstants.COL_UUID) 
    private UUID id; 

} 

@Entity 
public class UserItemFurniture extends UserItem { 

} 

現在我希望得到一個UserItemFurniture由其UUID,但只有當它存在於Useritems。這是我的嘗試:

em 
    .createQuery(
     "SELECT f " + 
     "FROM UserItemFurniture f " + 
     "WHERE f.id = :iid " + 
     "AND f IN (SELECT u.items FROM User u WHERE u.id = :uid) ", 
     UserItemFurniture.class 
    ) 
    .setParameter("uid", userId) 
    .setParameter("iid", itemId) 
    .getSingleResult(); 

但產生這種荒謬的SQL:

select useritemfu0_.id as id17_, useritemfu0_1_.item as item17_, useritemfu0_.roomNumber as roomNumber18_, useritemfu0_.x as x18_, useritemfu0_.y as y18_ 
from UserItemFurniture useritemfu0_ inner join UserItem useritemfu0_1_ on useritemfu0_.id=useritemfu0_1_.id 
where useritemfu0_.id=? and (useritemfu0_.id in (
    select . 
    from _User user1_, user_items items2_, UserItem useritem3_ 
    where user1_.id=items2_.user_id and items2_.useritem_id=useritem3_.id and user1_.id=? 
)) 
limit ? 

(注意子查詢:SELECT .

我能做到這一點,而不訴諸本地或多個查詢?請注意,UserItem沒有參考User,這是設計。

+2

你試過用'id'了'IN'條款限制?類似'... AND f.id IN(SELECT u.items.id FROM User ...' – 2013-02-08 14:50:57

+0

)不可能使用u.items.id,因爲作爲集合值路徑的項指的是整個集合,因此它沒有屬性id(即使收集的元素也有)。 – 2013-02-12 20:06:48

回答

1

以下查詢可用於:

SELECT f 
FROM UserItemFurniture f 
WHERE f.id = :uid AND EXISTS 
    (SELECT u FROM User u 
    WHERE u.id = :iid and f MEMBER OF u.items)