我在Hibernate中遇到了一个非常特殊的嵌套连接查询场景,应该相当简单,但我在缩小数据集方面遇到了麻烦。
我有一个如下表结构:
top bottom common
------------ ------------ ------------
id id top_id
... ... bottom_id
... ... common_value
lastUpdated lastUpdated date_added
目标是查询它,以便获得具有以下结构的对象:
top:
{ "id": 1,
"lastUpdated": "2016-05-01",
...
"bottom" : [ {
"id": 1
"lastUpdated": "2016-01-01",
...
"values": [ {
"top_id": 1,
"bottom_id": 1,
"common_value": "abc",
"date_added": "2016-05-15"
} ]
} ]
}
为此我有这些关系:
@Entity
@Table(name = "top")
public class Top {
@Id
@GeneratedValue(strategy = IDENTITY)
private Long id;
private String name;
//...other fields...
private Date updatedOn;
@OneToMany(fetch = FetchType.EAGER)
@JoinTable(name = "common",
joinColumns = @JoinColumn(name = "top_id"),
inverseJoinColumns = @JoinColumn(name = "bottom_id")
)
private Set<Bottom> bottomSet;
}
@Entity
@Table(name = "bottom")
public class Bottom {
@Id
@GeneratedValue(strategy = IDENTITY)
private Long id;
private String name;
//...other fields...
@OneToMany(fetch = FetchType.EAGER)
@JoinColumn(name = "bottom_id")
private Set<Common> values;
}
@Entity
@Table(name = "common")
public class Common {
@EmbeddedId
@AttributeOverrides({ @AttributeOverride(name = "top_id", column = @Column(name = "top_id") ),
@AttributeOverride(name = "common_value", column = @Column(name = "common_value", length = 32) ),
@AttributeOverride(name = "date_add", column = @Column(name = "date_added", length = 19) ),
@AttributeOverride(name = "bottom_id", column = @Column(name = "bottom_id") ) })
private CommonId id;
}
@Embeddable
public class CommonId {
private Integer top_id;
private String common_value;
private Date added_date;
private Integer bottom_id;
}
结果是结果结构包含了bottom_id所喜欢的所有值,结果太多了。我怎样才能使common_values的底部连接绑定到bottom_id和top_id?
非常感谢您的想法!
答案 0 :(得分:0)
解决了 -
关系没有改变,但是我没有查询所有顶级项目,而是创建了以下HQL来关联ID:
FROM Top t
INNER JOIN FETCH t.bottomSet b
INNER JOIN FETCH b.values v
WHERE t.id = :topId AND v.id.top_id = :topId