休眠:选择OneToMany关系中的位置

时间:2013-02-08 14:31:59

标签: java hibernate postgresql jpa jpql

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

@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 {

}

现在我希望通过其UUID获得UserItemFurniture,但前提是User的{​​{1}}。这是我的尝试:

items

但是它产生了这个荒谬的SQL:

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();

(注意子查询: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的引用,这是设计使然。

1 个答案:

答案 0 :(得分: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)