我有一個名爲item_association的Oracle表和一個附帶的Hibernate實體。下面是該錶行的例子:如何在Hibernate中的同一張表上做子查詢?
id group_id item_id type value
====================================
1 1 1234 'lang' 'en'
2 1 2345 'lang' 'fr'
我想查詢該表檢索共享與特定ITEM_ID一個GROUP_ID所有ItemAssociations,並排除ITEM_ID本身。該SQL將是:
select group_id, item_id, type, value
from ITEM_ASSOCIATION
where group_id in (select group_id from ITEM_ASSOCIATION where item_id = :itemId)
and item_id <> :itemId
我嘗試使用下面的Hibernate的標準來實現這一點,但我得到:org.hibernate.MappingException: Unknown entity: null
DetachedCriteria subquery = DetachedCriteria.forClass(ItemAssociation.class)
.add(Restrictions.eq("itemId", itemId))
.setProjection(Projections.property("groupId"));
Criteria query = session.createCriteria(ItemAssociation.class)
.add(Property.forName("itemId").in(subquery))
.add(Restrictions.not(Restrictions.eq("itemId", itemId)));
ItemAssociation.java:
@Entity
@Table(name = "ITEM_ASSOCIATION")
public class ItemAssociation {
@Id
@GeneratedValue
private Long id;
@Column(name = "group_id")
private Long groupId;
@OneToOne
@JoinColumn(name = "item_id", insertable = false, updatable = false)
private Item item;
@Column
private String type;
@Column
private String value;
public Long getGroupId() {
return groupId;
}
public void setGroupId(Long groupId) {
this.groupId = groupId;
}
public Item getItem() {
return item;
}
public void setItemId(Item item) {
this.item = item;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
我仍然可以使用Subqueries.propertyIn當上述MappingException。 – Jared