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?
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 theinverse
relationship back to the source object it would also be aManyToMany
relationship. All relationships in Java andJPA
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 throughforeign keys
and querying such that theinverse
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 twoprimary keys
of the main tables groups and users. This couple of fields is also called as acomposite primary key
.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.