【问题标题】:How to map a foreign key name on table with composite key?如何使用复合键在表上映射外键名称?
【发布时间】:2014-04-11 09:12:52
【问题描述】:

我想设置hibernate自动生成的外键约束名,所以不是fk_123213241341,而是fk_user

我正在尝试使用新的 JPA 2.1 注释 @ForeignKey。但我可能遗漏了一些东西:

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

【问题讨论】:

  • 你想做什么? User 在对象 UserPK 中有 id.firstnameid.lastname。那么许多trip 可以有一个User。所以在旅行中你可以得到user.id.firstnameuser.id.lastname。像这样?
  • 而您只想使用@ForeignKey 而不是@JoinColumns
  • @ForeignKey已弃用,因为最新的休眠版本依赖于 JPA 2.1
  • 是的,cz @javax.persistence.ForeignKey in JPA 2.1

标签: java sql hibernate jpa


【解决方案1】:

你需要使用@JoinColumns注解(注意's'):

class Trip {
    @ManyToOne
    @JoinColumns(foreignKey = @ForeignKey(name = "FK_USER")
    private User user;
}

【讨论】:

  • 嗯,不起作用:The annotation @JoinColumns must define the attribute value
  • 好的:@JoinColumns (foreignKey = @ForeignKey(name = "FK_USER"), value = { @JoinColumn(referencedColumnName = "firstname"), @JoinColumn(referencedColumnName = "lastname") })
猜你喜欢
  • 2017-01-30
  • 2019-04-22
  • 2017-02-21
  • 1970-01-01
  • 2016-06-05
  • 2018-11-28
  • 1970-01-01
  • 2011-05-29
  • 2011-03-20
相关资源
最近更新 更多