I'm mapping sql view to entity class with hibernate @Subselect
annotation.
Basically, it looks somewhat like this:
@Subselect(
"SELECT table1.*, table2.id as tid FROM "
+ "table1 INNER JOIN table2 on table2.field = table1.field"
)
@Entity
@Immutable
class Entity {
// fields
}
When the join works i may get something like the following
========================================
| table1.id | table1.field | table2.id |
========================================
| 1 | 1 | 1 |
========================================
| 1 | 1 | 2 |
========================================
So several records in table2 can join to one row in table1. This is fine, however in java Entity I want to map it as one to many relationship(one entity to many table2 enities), here's what I wrote, which worked for others kind of relationships:
@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<>();
}
However, the set in the entity is always empty, why is that ? The above approach works for one to one and many to one relationships.
Turns, it's not required to do join with sql, to bring one to many relationship for the view entity. I solved it like this:
Subselect(
"SELECT * from table1"
)
@Entity
@Immutable
class Entity {
@OneToMany
@JoinColumn(name = "field", updatable = false, insertable = false)
private Set<Table2Entity> elements = new HashSet<>();
}
I only needed to put column name, on which tables needed to be joined.