foreign key must have same number of columns as the referenced primary key for manytoone mapping

前端 未结 1 1053
清歌不尽
清歌不尽 2021-01-25 03:16

Hi below is my entities with manytoone association between them

student.java

@Entity
@Table(name = \"student\")
public class student{

    @Id
    @Colum         


        
相关标签:
1条回答
  • 2021-01-25 03:31

    To fix the issue, change your code like this:

     @ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.LAZY)
        @JoinColumns({
           @JoinColumn(name = "userrole_value", referencedColumnName = "VALUE"),
           @JoinColumn(name = "userrole_desc", referencedColumnName = "DESCRIPTION")
    
        })
        private studentdetails userrole;
    

    Reason for the issue: In mapping:

    @JoinColumns({
           @JoinColumn(name = "userrole", referencedColumnName = "VALUE"),
           @JoinColumn(name = "userrole_desc", referencedColumnName = "DESCRIPTION")
    
        })
    

    You are telling hibernate to create a foreign key in Student entity table called userrole that refers to the column called VALUE in StudentDetails entity table.

    Then in next line you are again telling hibernate to use the same colum name - userrole as FKey for the column DESCRIPTION in StudentDetails, so this line overrides the previous one.

    So hibernate sees that you are trying to have a single column as foreign key in Student entity table that maps to StudentDetails entity table. But the StudentDetails table has composite key made of 2 columns so hibernate throws an exception.

    org.hibernate.MappingException: Foreign key (FK6D56043A4415BDB5:student [userrole])) must have same number of columns as the referenced primary key (student_details [VALUE,DESCRIPTION])
    

    Additional information:

    You are trying to declare a composite Id for the entity StudentDetails, so this entity should implelemt Serializable interface and this is mandatory. Now this composite Id class should override equals() and hashcode() methods.

    Just a suggestion, try to follow Java naming conventions for your entities and fields.

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