gpt4 book ai didi

java - Hibernate 多重连接与公共(public)表

转载 作者:行者123 更新时间:2023-11-29 21:00:24 24 4
gpt4 key购买 nike

我在 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的底部连接绑定(bind)到bottom_id和top_id?

非常感谢您的想法!

最佳答案

解决了——

关系没有改变,但我没有查询所有顶级项目,而是创建了以下 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

关于java - Hibernate 多重连接与公共(public)表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37279727/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com