Spring Boot中的ManyToMany映射问题

问题描述 投票:2回答:1

我正在尝试在2个表用户和产品之间进行多对多映射。我写了他们的实体和存储库,但仍然是应用程序给出了错误。如果可以,请帮助我,提前谢谢。

错误

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

代码片段是

用户

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
java database hibernate spring-boot
1个回答
0
投票

在拥有的实体(Product)中,您传入拥有该关系的字段(在User实体中):

@ManyToMany(mappedBy = "products")
private Set<User> users = new HashSet< >();

最初你告诉持久性提供者在users实体中查找名为User的字段,该实体将保存关于该关系的所有信息(@JoinTable等)

© www.soinside.com 2019 - 2024. All rights reserved.