4

这些是我的(缩写)实体:

@Entity
public class User {

    @OneToMany(fetch=FetchType.LAZY)
    @JoinTable(name="user_items",joinColumns=@JoinColumn(name="user_id"),inverseJoinColumns=@JoinColumn(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 获取 a ,但前提是它存在 a User's items。这是我的尝试:

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,这是设计使然。

4

1 回答 1

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)
于 2013-02-12T19:59:18.670 回答