【发布时间】:2019-03-01 04:36:34
【问题描述】:
我正在使用 hibernate @Subselect 注释将 sql 视图映射到实体类。
基本上,它看起来有点像这样:
@Subselect(
"SELECT table1.*, table2.id as tid FROM "
+ "table1 INNER JOIN table2 on table2.field = table1.field"
)
@Entity
@Immutable
class Entity {
// fields
}
当加入工作时,我可能会得到如下内容
========================================
| table1.id | table1.field | table2.id |
========================================
| 1 | 1 | 1 |
========================================
| 1 | 1 | 2 |
========================================
所以 table2 中的几条记录可以连接到 table1 中的一行。这很好,但是在 java Entity 中我想将它映射为一对多关系(一个实体到多个 table2 实体),这是我写的,它适用于其他类型的关系:
@Subselect(
"SELECT table1.*, table2.id as tid FROM "
+ "table1 INNER JOIN table2 on table2.field = table1.field"
)
@Entity
@Immutable
class Entity {
@OneToMany
@JoinColumn(name = "tid", updatable = false, insertable = false)
private Set<Table2Entity> elements = new HashSet<>();
}
但是,实体中的集合总是空的,这是为什么呢? 上述方法适用于一对一和多对一关系。
【问题讨论】:
标签: java hibernate persistence one-to-many sql-view