我有三个 jpa 定义的表:“大陆”、“国家/地区”和“地区”。 它们具有整体部分关系,即。没有大陆,国家就不可能存在。 因此,我对大陆和国家/地区的类进行了建模,并且 spring 生成的 ddl 很好,一切正常:
@Entity
public class Continent {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Short id;
//[..]
}
@Entity
public class Country implements Serializable {
private static final long serialVersionUID = -6825504967607930373L;
@Id
@ManyToOne
@JoinColumn(name="continent_id")
private Continent continent;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Short id;
//[..]
}
但是如果我添加区域,我不知道如何定义关系而不让 hibernate 在初始化期间给我一个错误(见下文)。
@Entity
public class Region {
@Id
@ManyToOne
@JoinColumns({
// @JoinColumn(name="continent_id"),
@JoinColumn(name="country_id")
})
private Country country;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
Short id;
//[..]
}
这个定义给了我错误
Caused by: org.hibernate.MappingException: Foreign key (FK_otariwhls1krq0bo780jtvbqn:region [country_id])) must have same number of columns as the referenced primary key (country [id,continent_id])
at org.hibernate.mapping.ForeignKey.alignColumns(ForeignKey.java:110)
但是如果我从 Continental_id 连接列中删除//,则会收到此错误:
Caused by: org.hibernate.AnnotationException: A Foreign key refering com...Country from com...bo.Region has the wrong number of column. should be 1
at org.hibernate.cfg.annotations.TableBinder.bindFk(TableBinder.java:502)
我做错了什么?我在 Springboot 1.3 环境中的 mysql 上使用 Hibernate 4.3.11 Final。
最佳答案
仅使用@JoinColumn(name="country_id")
,不使用@JoinColumns
(注意复数),并从中删除@Id
Region.country
属性。
关于java - 具有 3 个表和复合主键的定义问题 JPA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33871459/