JPA:如何使用@MappedSuperclass和继承ID在子类之间构建ManyToMany关系

时间:2017-04-10 19:43:31

标签: jpa inheritance many-to-many eclipselink mappedsuperclass

我在构建我的应用程序的子类 - 实体之间的ManyToMany关系时遇到问题,该关系继承了超类的id(数据库id)字段以及其他2个变量。 @MappedSuperclass仅用于映射数据库表上的子类,每个子类Entity使用一个表。最后,我想在我提到的ManyToMany关系中生成一个Joined Table。

我无法弄清楚JoinTable注释的定义,我试图使用@AttributeOverride来覆盖每个子类中的继承ID。

你能指导我吗?

Person SUPERCLASS:

@MappedSuperclass
abstract public class Person {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY) 
    @Column(name = "id", nullable = false, updatable = false, unique=true)
    private int id;
    @Column(name = "First_Name")
    private String firstName;
    @Column(name = "Last_Name")
    private String lastName;

    //Constructors Goes Here...

    //Getters and Setters Goes Here....
}

Teacher SUBCLASS:

@Entity
@Table(name="Teacher")
@AttributeOverride(name = "id", column = @Column(name = "tid"))
public class Teacher extends Person {

    @Column(name="Teacher_Id", unique=true) 
    private int teacherId;
    @Column(name="Years_Experience")    
    private double yearsExperience;
    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name="Teachers_Students", 
    joinColumns=@JoinColumn(name="tid", referencedColumnName="tid"),
    inverseJoinColumns=@JoinColumn(name="sid", referencedColumnName="sid")) 

    private ArrayList<Student> students = null;

    //Constructors Goes Here...

    //Getters and Setters Goes Here...
}

学生SUBCLASS:

@Entity
@Table(name="Student")
@AttributeOverride(name = "id", column = @Column(name = "sid"))
public class Student extends Person {

    @Column(name="Student_Id", nullable = false, unique=true)
    private int studentId;
    @Column(name="Year_Average_Grade")
    private double yearAverageGrade; 
    @ManyToMany(mappedBy = "students", cascade = CascadeType.ALL)
    ArrayList<Teacher> teachers= null;

    //Constructors Goes Here...

    //Getters and Setters Goes Here...
}

0 个答案:

没有答案