java - 使用 @OneToMany 或 @ManyToMany 将未映射的类作为 List在 Spring 数据 jpa 中
问题描述
我正在尝试使用 CrudRepository 实现 Spring data jpa 。下面是我的实体类
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id = null;
@OneToMany
@ElementCollection
@CollectionTable(name="photoUrls")
@Valid
private List<String> photoUrls = new ArrayList<String>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public List<String> getPhotoUrls() {
return photoUrls;
}
public void setPhotoUrls(List<String> photoUrls) {
this.photoUrls = photoUrls;
}
}
并有一个如下的存储库,
public interface UserRepository extends CrudRepository<User, Long>{
}
并尝试使用 h2 数据库进行本地测试
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
并从 CommandLineRunner 调用 UserRepository 的保存方法,但出现以下错误,
引起:org.hibernate.AnnotationException:使用@OneToMany 或@ManyToMany 以未映射的类为目标:org.hibernate.cfg.annotations.CollectionBinder.bindManyToManySecondPass(CollectionBinder.java:第1191章~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]在org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(CollectionBinder.java:794)~[hibernate-core-5.0.12 .Final.jar:5.0.12.Final]
解决方案
Hibernate 支持三种数据映射类型:basic(例如String、int)、Embeddable 和Entity。大多数情况下,一个数据库行映射到一个实体,每个数据库列都与一个基本属性相关联。当将多个字段映射组合成一个可重用组(Embeddable 被合并到拥有的实体映射结构中)时,可嵌入类型更为常见。
基本类型和 Embeddables 都可以通过@ElementCollection
,在一个实体-多-非实体关系中与实体相关联。
@ElementCollection
@CollectionTable(name="photoUrls",
joinColumns = @JoinColumn(name = "user_id"))
@Valid
private List<String> photoUrls = new ArrayList<String>();
因此,您需要删除@OneToMany
OneToMany 是针对单实体多实体关系。如果要映射到实体,则需要更改如下代码并创建新的实体照片。
@OneToMany(
cascade = CascadeType.ALL,
orphanRemoval = true
)
private List<Photo> photos = new ArrayList<>();
在上面的代码中,Photo 是一个实体。
有关更多信息,请参阅以下链接: https ://vladmihalcea.com/how-to-optimize-unidirectional-collections-with-jpa-and-hibernate/
推荐阅读
- sass - Bootstrap 4 - 添加文本轮播指示器
- javascript - 如何使用浏览器的 PDF 查看器打开 PDF Blob 而不是下载?
- reactjs - 使用 Typescript 在 React 中作为状态的两个字符串之一
- mysql - 以汇总方式连接不相关的表
- visual-studio-code - VSCode 上的运算符周围的间距
- amazon-s3 - 如何为 AWS S3 存储桶禁用 TLS 1.0
- scala - 为什么在运行sbt打包的jar文件时会出现这个jni错误?
- session - Apache Tomee 会话管理与 gemFire 集成
- amazon-web-services - AWS lambda nodejs 在使用 X-RAY 时显示错误
- python - 烧瓶 whooshalchemy 错误:ModuleNotFoundError:没有名为“flask.ext”的模块