Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map a foreign key name on table with composite key?

I'd like to set the foreign key constraint name that is autogenerated by hibernate, so that is not named fk_123213241341, but fk_user.

I'm trying to use the new JPA 2.1 Annotation @ForeignKey. But I'm missing probably something:

org.hibernate.AnnotationException: A Foreign key refering User from Trip has the wrong number of column. should be 2

@IdClass(UserPK.class)
class User {
    @Id
    String firstname;

    @Id
    String lastname;

    //other fields omitted
}

class UserPK {
    String firstname;
    String lastname;
}

class Trip {
    @ManyToOne
    @JoinColumn(foreignKey = @ForeignKey(name = "FK_USER")
    private User user;
}
like image 401
membersound Avatar asked Nov 22 '25 12:11

membersound


1 Answers

You need to use the @JoinColumns annotation (note the 's'):

class Trip {
    @ManyToOne
    @JoinColumns(foreignKey = @ForeignKey(name = "FK_USER")
    private User user;
}
like image 183
Brian Vosburgh Avatar answered Nov 24 '25 01:11

Brian Vosburgh