Skip to content
Advertisement

org.hibernate.MappingException: collection foreign key mapping has wrong number of columns

I have a class Subject as such,

@Entity
@IdClass(SubjectId.class)
@Data
public class Subject {
    @Id
    private String name;
    @ManyToOne
    @JsonBackReference
    @Id
    private Teacher teacher;
    @OneToMany(mappedBy = "student")
    private List<StudentSubject> students;
}

Its composite Id is defined in SubjectId class as such,

public class SubjectId implements Serializable{
    private String name;
    private Teacher teacher;

    public SubjectId(String name, Teacher teacher) {
        this.name = name;
        this.teacher = teacher;
    }
    SubjectId(){}
}

On compiling, I get the error

org.hibernate.MappingException: collection foreign key mapping has wrong number of columns: com.example.Subject.students type: component[name,teacher]

While this points the error to students element, the error occured after I removed the autogenerated id of Subject, and replaced it with combination of name and teacher.

Anyway, students element is mapped in StudentSubject class as such,

@Entity
@IdClass(StudentSubjectId.class)
public @Data
class StudentSubject {

    String studentId;
    @ManyToOne
    @Id
    private Subject subject;
    @ManyToOne
    @Id
    private Student student;

Advertisement

Answer

When this error occurs, it generally means that hibernate is having problem mapping foreign keys on a right number of columns.

In above case, the subject entity in StudentSubject class was not getting mapped to two columns, that is the name and teacher_email(which is the primary key of Teacher table).

To fix such errors, add @JoinColumns as below

class StudentSubject {
    @Id
    @ManyToOne
    @JoinColumns({
            @JoinColumn(referencedColumnName = "name"),
            @JoinColumn(referencedColumnName = "teacher_email") })
    private Subject subject;
}

The referencedColumnName refers to the name of the column in the foreign table.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement