【问题标题】:Hibernate creates two tables in a many to many relationshipHibernate 在多对多关系中创建两个表
【发布时间】:2020-07-18 09:53:02
【问题描述】:

这是我的Product实体类:

public class Product extends BaseEntity {
  @Column
  @ManyToMany()
  private List<Customer> customers = new ArrayList<>();

  @ManyToOne
  private Supplier supplier;
} 

这是我的Customer实体类:

public class Customer extends BaseEntity {

  //Enum type to String type in database '_'
  @Enumerated(EnumType.STRING)
  @Column
  private Type type;

  @Column
  @ManyToMany(targetEntity = Product.class)
  private List<Product> products = new ArrayList<>();
}

当我运行我的 Spring Boot 项目时,它会在我的数据库 (Mysql) 中创建 2 个单独的表:product_customercustomer_product 但我只需要一个。我该怎么做才能解决这个问题?

【问题讨论】:

  • 没有@JoinTable,这不是双向关系,而是双方的两个单向关系,这就是创建两个表的原因。尝试用@JoinTable定义连接表

标签: spring spring-boot hibernate jpa spring-data-jpa


【解决方案1】:

如下更新您的课程:

   public class Product {

     @ManyToMany
     @JoinTable(name="product_customer"
            joinColumns=@JoinColumn(name="product_id"),
            inverseJoinColumns=@JoinColumn(name="customer_id")
     )
     private List<Customer> customers = new ArrayList<>();
     ...
   }
    public class Customer extends BaseEntity {

      @ManyToMany
      @JoinTable(name="product_customer"
            joinColumns=@JoinColumn(name="customer_id"),
            inverseJoinColumns=@JoinColumn(name="product_id")
      )
      private List<Product> products = new ArrayList<>();
      ...
    }

【讨论】:

  • 我认为在客户大小@ManyToMany(mappedBy = "customers") 就足够了
  • 是的。一旦他将一方确定为拥有方。我将保留答案,因为@doctore 已将其作为答案
  • 在我的回答中添加了一个更新,以澄清这一点 @AliBooresh
  • @dotore,谢谢。我们都在这里互相学习
【解决方案2】:

看看下面的link 以了解如何以合适的方式映射ManyToMany 关系。但基本上,你可以这样做:

public class Product {
  ...

  @ManyToMany(cascade = {
    CascadeType.PERSIST,
    CascadeType.MERGE
  })
  @JoinTable(name="product_customer"
    joinColumns=@JoinColumn(name="product_id"),
    inverseJoinColumns=@JoinColumn(name="customer_id")
  )
  private Set<Customer> customers = new LinkedHashSet<>();

  ...
}

还有:

public class Customer extends BaseEntity {

  ...
  @ManyToMany(mappedBy = "customers")
  private Set<Product> products = new LinkedHashSet<>();

  ...
}

正如@Kavithakaran 在他的回答的评论中提到的那样,一旦您确定“关系的所有者”,您就可以使用@ManyToMany(mappedBy = ...

【讨论】:

    【解决方案3】:

    如果您的意思是不想创建第三个表,那么您可以阅读以下链接:- Hibernate Many to Many without third table

    否则,您可以使用@jointable 注解来做到这一点。

    【讨论】:

      猜你喜欢
      • 2017-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-07
      • 2018-03-06
      • 2019-10-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多