我创建了两个类,它们之间有多对多关系,如下所示:
@Entity
@Table(name = FoodEntity.TABLE_NAME)
public class FoodEntity extends BaseEntity<Long> {
public static final String TABLE_NAME = "T_FOOD";
@ManyToMany
@JoinTable(
name = "T_FOOD_FOODCATEGORY",
joinColumns = { @JoinColumn(name = "FOOD_ID") },
inverseJoinColumns = { @JoinColumn(name = "FOOD_CATEGORY_ID") })
private Set<FoodCategoryEntity> categories;
public Set<FoodCategoryEntity> getCategories() {
return categories;
}
public void setCategories(Set<FoodCategoryEntity> categories) {
this.categories = categories;
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "FOOD_ID", nullable = false)
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
}
和:
@Entity
@Table(name = FoodCategoryEntity.TABLE_NAME)
public class FoodCategoryEntity extends BaseEntity<Long> {
public static final String TABLE_NAME = "T_FOOD_CATEGORY";
@ManyToMany(mappedBy = "categories")
private Set<FoodEntity> foods;
public Set<FoodEntity> getFoods() {
return foods;
}
public void setFoods(Set<FoodEntity> foods) {
this.foods = foods;
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "FOOD_CATEGORY_ID", nullable = false)
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
}
但是当我用junit,spring和hibernate测试这个关系时,我得到以下异常:
Caused by: org.hibernate.MappingException: Could not determine type for: java.util.Set, at table: T_FOOD, for columns: [org.hibernate.mapping.Column(categories)]
at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:455)
at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:422)
at org.hibernate.mapping.Property.isValid(Property.java:226)
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:597)
at org.hibernate.mapping.RootClass.validate(RootClass.java:265)
at org.hibernate.boot.internal.MetadataImpl.validate(MetadataImpl.java:329)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:451)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:889)
... 46 more
我检查了注释包引用和所有ID列名,但所有这些都是正确的。 point:我还使用HSQLDB数据库,它的存储位置是文件。
答案 0 :(得分:2)
我发现了我的问题。 persistence.xml中的映射类不正确。
答案 1 :(得分:0)
您的注释推断属性访问类型映射,因为@Id
放置在getter
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "FOOD_ID", nullable = false)
@Override
public Long getId() {
return id;
}
但收集注释放在字段级别
@ManyToMany
@JoinTable(
name = "T_FOOD_FOODCATEGORY",
joinColumns = { @JoinColumn(name = "FOOD_ID") },
inverseJoinColumns = { @JoinColumn(name = "FOOD_CATEGORY_ID") })
private Set<FoodCategoryEntity> categories;
虽然在getter上指定了(未)有效配置
public Set<FoodCategoryEntity> getCategories() {
return categories;
}
您不应混用两种类型的配置。