Now look I have some points : Three Entites you have : School , Workshop , Teacher. School have oneTomany with - workshop & teacher. So once we are persisting school we'll have entries in both the tables - workshop & teacher.And also you wanted to have A Workshop Entity has a single Host School so we achieved that also while persisting as per below code.
Your School Entity :
@Entity
public class School
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long ID;
@OneToMany(cascade = CascadeType.PERSIST, mappedBy="school")
private List<Teacher> teachers;
@OneToMany(cascade = CascadeType.PERSIST,mappedBy="school")
private List<Workshop> workshops;
// Getters and Setters and some methods
}
Your Teacher Entity:
@Entity
public class Teacher
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Key key;
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="key")
private School school;
// Getters and Setters and some methods}
Your WorkShop Entity:
@Entity
public class Workshop
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Key key;
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="key")
private School school;
and then :
em.getTransaction().begin();
School schoolObj = new School();
schoolObj.setName("School 1");
List <Teacher> teachers = new ArrayList<Teacher>();
List <Workshop> workshopList = new ArrayList<Workshop>();
Teacher teacher = new Teacher();
teacher.setSchool(schoolObj);
teacher.setName("Teacher 1");
teachers.add(teacher);
Teacher teacher1 = new Teacher();
teacher1.setSchool(schoolObj);
teacher1.setName("Teacher 2");
teachers.add(teacher1);
teacher teacher2 = new Teacher();
teacher2.setSchool(schoolObj);
teacher2.setName("Teacher 3");
teachers.add(teacher2);
Workshop ws = new Workshop();
ws.setSchool(schoolObj); //By this you setted schoolObj in workshop entity
ws.set(some attribute);
workshopList.add(ws);
school.setTeachers(teachers); //By this you setted teachers through school ,i.e., entry came in teachers table too.
school.setWorkshops(workshopList); //By this you setted workshopList through school ,i.e., entry came in workshop table too.
em.persist(schoolObj);
em.getTransaction().commit();
em.close();
Now you mentioned that: A WorkShop Entity also has a List of participants .And A Teacher Entity had a List they attended and an employment history List. This shows you are having ManyToMany between Workshop & Teacher. As in your case Workshop has List of teachers and Teachers also have List of Workshop's.So here you will be requiring a joining table to lonk this ManyToMany relationship. Similarly, between teacher & school you have ManyToMany as both have List of one other.So here also you will be needing joining table.To learn more about this click here. Hence to set this ManyToMany relationship you have to link through a joining table not by persisting here as it will clash then. And if you want to fetch data as per this ManyToMany relationship then you have make a separate query. Hope this help !