以下是我(缩写)的实体:
@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
的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
的引用,这是有意为之。
...AND f.id IN (SELECT u.items.id FROM User ...
- Xavi López