JPA中@ElementCollection嵌套@Embeddable报错的解决方法咨询
问题原因
JPA规范明确限制:被@ElementCollection引用的@Embeddable类内部,不能再嵌套@ElementCollection。你的代码里Grade是@Embeddable,被School的@ElementCollection包含,但Grade里又定义了@ElementCollection来映射Class集合,这直接违反了规范,所以抛出错误。
修复方案(推荐)
把Grade从@Embeddable改为@Entity,用一对多关联替代原有的@ElementCollection,这样就能合法嵌套Class的集合映射。
修改后的完整代码:
School类
@Entity public class School { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer schoolId; // 其他字段... @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) @JoinColumn(name = "schoolId") private Set<Grade> grades; }
Grade类
@Entity public class Grade { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer gradeId; // 其他字段... @ElementCollection @CollectionTable( name = "class", joinColumns = @JoinColumn(name = "gradeId") ) private Set<Class> classes; }
Class类(修正拼写错误)
@Embeddable public class Class { private int numOfStudent; private int female; private int male; // 原代码"mamle"拼写错误,已修正 }
补充说明
- 用
@OneToMany关联School和Grade时,加上cascade = CascadeType.ALL可以让学校的操作级联到年级,orphanRemoval = true会自动删除与学校解除关联的年级数据。 - 原代码里的字段拼写错误(
mamle)和缺失的分号也要修正,避免额外编译错误。
内容的提问来源于stack exchange,提问作者Andrew Oh
相关产品推荐
相关产品推荐

