我有以下两个带有这些注释的类(及其 pk 类)。我删除了 setters/getters/hashcode/equals 来压缩示例
我最终收到了这个错误
org.hibernate.MappingException:集合映射中的重复列:com.stackOverflow.Features.thingCategory列:YEAR
我的猜测是,因为“年份”在连接表中共享,所以我搞乱了一些关联实体的语法。请注意,这些 View 在其实体之间具有隐式关系,我试图在注释中对其进行建模。我尝试过一些 JPA 建模工具,这些工具在建模后给我同样的错误。我也尝试将连接列设置为 insertable
和 updatable
为 false
。
我当然可以只编写一个 SQL 查询,但我真的很惊讶在 Hibernate 中这对我来说有多难。
功能实体
@Entity
@Table(name = "myTableOfFeatures")
public class Feature {
private static final long serialVersionUID = 1L;
@EmbeddedId
private FeatureKey id;
@Column(name="displayText")
private String description;
//bi-directional many-to-many association
@ManyToMany
@JoinTable(
name="joinTableToThingCategories"
, joinColumns={
@JoinColumn(name="name", referencedColumnName="name", insertable = false, updatable = false),
@JoinColumn(name="year", referencedColumnName="year", insertable = false, updatable = false)
}
, inverseJoinColumns={
@JoinColumn(name="year", referencedColumnName="year", insertable = false, updatable = false),
@JoinColumn(name="title", referencedColumnName="title", insertable = false, updatable = false)
}
)
private List<ThingCategory> thingCategory;
public Feature() {
}
// ... gets and sets
}
@Embeddable
public class FeatureKey implements Serializable {
//default serial version id, required for serializable classes.
private static final long serialVersionUID = 1L;
@Column(name="name")
private String myName;
private String year;
public FeatureKey() {
}
// ... gets and sets and equals and hashes
}
事物类别实体
@Entity
@Table(name = "CategoriesOfThings")
public class ThingCategory implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
private ThingCategoryKey id;
private String comment;
//bi-directional many-to-many association to categories
@ManyToMany(mappedBy="thingCategory")
private List<Feature> features;
public ThingCategory() {
}
// ... gets and sets
}
@Embeddable
public class ThingCategoryKey implements Serializable {
//default serial version id, required for serializable classes.
private static final long serialVersionUID = 1L;
private String year;
@Column(name="categoryName")
private String title;
public ThingCategoryKey() {
}
// ... gets and sets and equals and hashes
}
最佳答案
这是 JPA 2.1 规范的示例。 我希望它有帮助。
@Entity
public class Employee {
@Id int id;
@Embedded ContactInfo contactInfo;
...
}
@Embeddable
public class ContactInfo {
@ManyToOne Address address; // Unidirectional
@ManyToMany List<PhoneNumber> phoneNumbers; // Bidirectional
}
@Entity
public class PhoneNumber {
@Id int phNumber;
@ManyToMany(mappedBy="contactInfo.phoneNumbers")
Collection<Employee> employees;
}
我强烈推荐您这个规范。 JPA 2.1
关于java - 多对多 JPA Hibernate 通过连接表映射复合键错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38333552/