JPA OneToOne and ManyToMany between two entities

前端 未结 2 1167
庸人自扰
庸人自扰 2020-12-22 14:39

I asked a question earlier, but think it wasn\'t clear enough i will elaborate further with the code.
I have a Teacher entity and Department entity
Many Teachers

相关标签:
2条回答
  • 2020-12-22 15:29

    I removed the @oneToOne relationship between Teacher and Department and created a new entity called DepartmentHeads, everything now works fine.
    Here is the Results.

    @Entity
    public class Teacher extends Model {
        @Required
        public String surname;
    
        @Required
        public String othernames;
    
        ... 
    
        @ManyToOne(cascade=CascadeType.ALL)
        public Department dept = new Department();
    
        ... 
    }
    
    @Entity
    public class Department extends Model {
        @Required
        public String deptName; 
    
        @OneToMany(mappedBy="dept")
        public List<Teacher> teachers = new ArrayList<Teacher>();
    
        ...
    
    }
    
    @Entity
    public class DepartmentHead extends Model{
        @OneToOne
        public Teacher teacher = new Teacher();
    
        @OneToOne
        public Department dept = new Department();  
    }
    

    Everything now works fine.

    0 讨论(0)
  • 2020-12-22 15:30

    This is not a JPA problem, but is caused by recursive instantiation of Teacher/Department.

    When you create, or ask JPA to create, an instance of Teacher, the Teacher attempts to instantiate a Department, which instantiates a Teacher ..., to infinity.

    Hence you're seeing a StackOverflowError error near the end of that stack trace.

    Remove the = new Teacher() and = new Department() expressions from the class definition; depend on and use appropriate setter methods when you create them.

    0 讨论(0)
提交回复
热议问题