Hibernate creates two tables in a many to many relationship

Viewed 2088

This is my Product entity class:

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

  @ManyToOne
  private Supplier supplier;
} 

And this is my Customer entity class:

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

When I run my Spring boot project, it creates 2 separate tables in my database(Mysql): product_customer and customer_product but I need only one. What can I do to solve this?

3 Answers

Update your classes as follows:

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

Take a look to the following link to know how to map a ManyToMany relation in a suitable way. But basically, you can do:

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

  ...
}

And:

public class Customer extends BaseEntity {

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

  ...
}

As @Kavithakaran mentioned in a comment of his answer, you can use @ManyToMany(mappedBy = ... once you identify the "owner of the relation".

Related