Issue
I have 4 Tables: Table1, Table2, Table3, Table4.
- Table1 has a many to one relation to Table2
- Table2 has a many to one relation to Table3
- Table3 has a one to many relation to Table4
My intent is that Table1 will have a many-to-many member to Table4. That is, Table1 will have a List member of Table4's
public class Table1 implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(updatable = false, nullable = false)
@JsonView(View.class)
private UUID id;
List<Table4> list; //This is the member of the question
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "table_2_id")
@JsonView(View.class)
private Table2 table2;
....
}
public class Table2 implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(updatable = false, nullable = false)
@JsonView(View.class)
private UUID id;
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "table_3_id")
@JsonView(View.class)
private Table3 table3;
}
public class Table3 implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(updatable = false, nullable = false)
@JsonView(View.class)
private UUID id;
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "table_4_id")
@JsonView(View.class)
private Table4 table4;
}
public class Table4 implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(updatable = false, nullable = false)
@JsonView(View.class)
private UUID id;
....
}
I have attempted to use something like
@JoinTable(
name = "Table3",
joinColumns = @JoinColumn(name = "table_2_id"),
inverseJoinColumns = @JoinColumn(name = "table_4_id")
)
... in an attempt for mapping Many to Many entities, but this approach doesn't seem like it will work since I have two intermediate tables.
How can I grab a list from a table that is a few tables away with a many to many relation?
Solution
Why not just have a getter method that returns your list of Table4, like bellow? You already have all the mappings in place.
public class Table1 implements Serializable {
...
public List<Table4> getTable4List(){
//navigate to the list of table4 through the other tables
//return null (or empty list) if table2, table3 are null or empty
}
You can put the getter in the entity to follow domain driven design but you can also put this in a service transactional method...
Answered By - GabiM
Answer Checked By - Candace Johnson (JavaFixing Volunteer)