Is it possible to bind two entities as ManyToMany without extra class?

245 Views Asked by At

I have two entities, say,

@Entity
@Table(name = "products")
public class Products {
    // ...
}

and

@Entity
@Table(name = "customers")
public class Customer {
    // ...
}

In the database, I have tables customers, products and customers_products, which, respectively, store data about customers, products and their relations.

That hold many-to-many relationship (a customer can add multiple products, and each product can be added by multiple customers). So I add private properties to each of entities and annotate them as @ManyToMany.

Should I, after that, explicitly add a class ProductCustomer that mimics DB table products_customers, or would a proper @ManyToMany config be enough? In case the latter, what direction should I look to find the answer?

1

There are 1 best solutions below

1
On

A ManyToMany relationship in Java is where the source object has an attribute that stores a collection of target objects and (if) those target objects had the inverse relationship back to the source object it would also be a ManyToMany relationship. All relationships in Java and JPA are unidirectional, in that if a source object references a target object there is no guarantee that the target object also has a relationship to the source object. This is different than a relational database, in which relationships are defined through foreign keys and querying such that the inverse query always exists.

Typically, a join table is created to connect two primary tables in order to make the association.

Normally the join table has only two fields (entity_A_id and entity_B_id) that refer to two primary keys of the main tables groups and users. This couple of fields is also called as a composite primary key.

Until this, going with two classes is absolutely fine, no need of creating and managing the 3rd joint class.

Now, let suppose you wish to modify the Joint Table, meaning entering more fields into it etc. The you need to create the 3rd class, with table name same as joint table name.

for ref.