【问题标题】:ManyToMany mapping issue in Spring BootSpring Boot 中的多对多映射问题
【发布时间】:2018-06-01 23:42:18
【问题描述】:

我正在尝试在 usersproducts 两个表之间进行多对多映射。我写了他们的实体和存储库,但应用程序仍然出错。如果可以的话,请帮助我,在此先感谢。

错误

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

【问题讨论】:

    标签: java database hibernate spring-boot


    【解决方案1】:

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

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

    最初您告诉 Persistence 提供程序在 User 实体中查找名为 users 的字段,该字段将保存有关关系的所有信息(@JoinTable 等)

    【讨论】:

    • 这就像一个魅力!非常感谢。如果你有空闲时间,你能解释一下为什么我们需要做这个改变吗?
    猜你喜欢
    • 2018-02-26
    • 2021-08-22
    • 2016-02-17
    • 2012-02-21
    • 2016-06-30
    • 1970-01-01
    • 2020-11-30
    • 2011-10-09
    • 1970-01-01
    相关资源
    最近更新 更多