Ali Booresh
Ali Booresh

Reputation: 53

Hibernate creates two tables in a many to many relationship

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?

Upvotes: 3

Views: 4616

Answers (3)

user731136
user731136

Reputation:

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".

Upvotes: 2

prachi julka
prachi julka

Reputation: 76

If you mean that you don't want to create the third table then you can read the following link below:- Hibernate Many to Many without third table

Otherwise, you can do this with @jointable annotation.

Upvotes: 1

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

Upvotes: 4

Related Questions