Spring Boot 中的多对多映射问题
Posted
技术标签:
【中文标题】Spring Boot 中的多对多映射问题【英文标题】:ManyToMany mapping issue in Spring Boot 【发布时间】:2018-06-01 23:42:18 【问题描述】:我正在尝试在 users 和 products 两个表之间进行多对多映射。我写了他们的实体和存储库,但应用程序仍然出错。如果可以的话,请帮助我,在此先感谢。
错误
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: com.poc.joins.entities.User.users in com.poc.joins.entities.Product.users
代码sn-ps是
用户
package com.poc.joins.entities;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
@Entity
@Table(name = "users")
public class User
@Id
private String username;
private String password;
@ManyToMany(cascade = CascadeType.MERGE)
@JoinTable(name = "users_products",
joinColumns = @JoinColumn(name = "username"),
inverseJoinColumns = @JoinColumn(name = "id"))
private Set<Product> products = new HashSet<>();
// Getter, setters, constructors are not shown here
产品
package com.poc.joins.entities;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
@Entity
@Table(name = "products")
public class Product
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String p_name;
private Integer quantity;
private Float price;
private Float total;
@ManyToMany(mappedBy = "users")
private Set<User> users = new HashSet< >();
// Getter, setters, constructors are not shown here
【问题讨论】:
【参考方案1】:在拥有的实体 (Product
) 中,传入拥有关系的字段(在 User
实体中):
@ManyToMany(mappedBy = "products")
private Set<User> users = new HashSet< >();
最初您告诉 Persistence 提供程序在 User
实体中查找名为 users
的字段,该字段将保存有关关系的所有信息(@JoinTable 等)
【讨论】:
这就像一个魅力!非常感谢。如果你有空闲时间,你能解释一下为什么我们需要做这个改变吗?以上是关于Spring Boot 中的多对多映射问题的主要内容,如果未能解决你的问题,请参考以下文章