At a high level, I have a class "MainClass" that has a list of "OtherEntity". There are essentially two join tables. The two join tables have meta-data in them that other components use but I have not defined entities for as we don't need them outside of a join operation. But basically MainClass => TableOne => TableTwo => OtherEntity
My entity definitions
@Entity
public class MainClass {
// other stuff ...
// how to?
@OneToMany
private List<OtherEntity> otherEntities;
}
@Entity
public class OtherClass { // other stuff ... }
My schema (legacy and cannot be modified)
table MainClass
PK id
...
table TableOne
PK id
FK main_class_id
FK table_two_id
table TableTwo
PK id
FK table_one_id
FK other_entity_id
table OtherEntity
PK id
...
I'd like avoid creating entities for TableOne and TableTwo if I could.
Consider using @SecondaryTable it should work for legacy schemas, using this annotation you can have fields in one entity, and just define which ones will form part of other table, but you only have 2 entities.
Check this tutorial
Idea is split fields from one entity in different tables without need the creation of other entities, just define which fields are in which table.
@SecondaryTables{@SecondaryTable(name="XX")}
and to move fields between tables use
@Column(table="XX")
In your config try something like this.
@Entity
@SecondaryTables{@SecondaryTable(name="TableOne"), @SecondaryTable(name="TableTwo")}
table MainClass
PK id
@Column(table="TableOne")
FK main_class_id
@Column(table="TableOne")
FK table_two_id
@Column(table="TableTwo")
PK id
@Column(table="TableTwo")
FK table_one_id
@Column(table="TableTwo")
FK other_entity_id
For ID in middle tables consider remove @Id and set it automatically, it should work !!
The issue is a design problem that will eventually be addressed. We have a database view that provides a unified look up table. In the database layer we can assign the pieces individually.
@Entity
public class MainClass {
@OneToMany
@JoinTable(name = "TheViewName",
joinColumns = @JoinColumn(name = "id", insertable = false, updatable= false),
inverseJoinColumns = @JoinColumn(name = "other_id", insertable = false,
updatable = false))
private List<OtherEntity> otherEntities;
}
This means I cannot assign a new other entity to the MainClass and persist both. I have to do two separate operations to get things finalized. But, that will go away when we refactor the schema.
Alternatively, we could create entities for the other two tables to make the operations more transparent.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.