首页 > 解决方案 > 使用 @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]

标签: javaspringspring-boothibernatehibernate-mapping

解决方案


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>();

因此,您需要删除@OneToManyOneToMany 是针对单实体多实体关系。如果要映射到实体,则需要更改如下代码并创建新的实体照片。

@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/


推荐阅读