JavaDev
JavaDev

Reputation: 442

JPA Hibernate - Foreign Key as Primary Key

I have no control of DB structure. But it was designed like this. A Person is like the base of all types of person. Then a Teacher class is created, whose PK references Person's PK also. The problem is when I reference the Teacher from another class, I get "has the wrong number of column. should be 0" error.

Kindly help what is best 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;
}

Upvotes: 0

Views: 1843

Answers (1)

JamesENL
JamesENL

Reputation: 6540

Implement the following:

@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;

    ....
}

This config will give you a table called Person with a Primary Key called personId, and a table called Teacher that only contains the specific fields of a teacher. You can save a teacher and you will get the teacher specific stuff in Teacher with all your other stuff in the Person table. If it is unclear what this is doing, please tell me so I can refine my explanation.

Upvotes: 2

Related Questions