JPA Hibernate - 外键作为主键

时间:2014-05-20 04:37:43

标签: hibernate jpa

我无法控制数据库结构。但它的设计是这样的。一个人就像是所有类型人的基础。然后创建一个Teacher类,其PK也引用Person的PK。问题是当我从另一个类引用教师时,我得到“列数错误。应该是0”错误。

请帮助最好的appraoch。

@Entity
@Table( name = "APP_Person" )
Person {
    @Id
    @GeneratedValue( strategy = GenerationType.IDENTITY )
    @Column( name = "PersonID", unique = true, nullable = false )
    private Long personID;

    @Column( name = "Name", length = 160 )
    @Size( max = 160 )
    private String name;
}

@Entity
@Table( name = "APP_Teacher" )
public class Teacher implements Serializable
{

    private static final long serialVersionUID = 1L;

    @Id
    @ManyToOne( fetch = FetchType.LAZY )
    @NotBlank
    @JoinColumn( name = "PersonID", nullable = false )
    Person person;

    @Column( name = "Expertise", length = 160 )
    @Size( max = 160 )
    private String expertise;
}

@Entity
@Table( name = "APP_Course" )
public class Course implements Serializable
{

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue( strategy = GenerationType.IDENTITY )
    @Column( name = "CourseID", unique = true, nullable = false )
    private Long courseID;

    @ManyToOne( fetch = FetchType.LAZY )
    @NotBlank
    @JoinColumn( name = "PersonID", unique = true, nullable = false )
    Teacher teacher;
}

1 个答案:

答案 0 :(得分:1)

实施以下内容:

@Entity
@Table(name = "Teacher")
@PrimaryKeyJoinColumn
public class Teacher extends Person{
    /* 
     * Note that Teacher doesn't have a PK, 
     * that's because its on the Person table
     */

    @Column( name = "Expertise", length = 160 )
    @Size( max = 160 )
    private String expertise;
}

@Entity
@Table(name = "Person")
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class Person{
    @Id
    @GeneratedValue( strategy = GenerationType.IDENTITY )
    @Column( name = "PersonID", unique = true, nullable = false )
    private Long personID;

    @Column( name = "Name", length = 160 )
    @Size( max = 160 )
    private String name;

    ....
}

此配置将为您提供一个名为Person的表,其中包含名为personId的主键,以及一个名为Teacher的表,该表仅包含教师的特定字段。您可以保存一名教师,您将获得教师中的教师特定内容以及Person表中的所有其他内容。如果不清楚这是做什么的,请告诉我,以便我可以改进我的解释。