Q1. How can we model triple relationships using Hibernate? For example, how can we model the triple relationships presented here using Hibernate (or JPA)? (...)
I would redo the relationship with an intermediate entity class (and what is recommended with Hibernate). Applies to your example:
@Entity public class Sale { @Embeddable public static class Pk implements Serializable { @Column(nullable = false, updatable = false) private Long soldById; @Column(nullable = false, updatable = false) private Long buyerId; @Column(nullable = false, updatable = false) private Long productId; public Pk() {} public Pk(Long soldById, Long buyerId, Long productId) { ... }
B1.1. How can we model this option in which each Sale element can have many products?
I would not use a composite primary key here and enter PK for the Sale object.
Q2. In general, how can we model n-ary, n> = 3 relationships with Hibernate?
I think my answer is Q1. covers it. If not, please specify.
Update: Responding to OP comments
(...) pk fields are not filled, and as a result, I can not save sales objects in the database. Should I use setters like this for the Sale class? public void setBuyer (Client cust) {this.buyer = cust; this.pk.buyerId = cust.getId (); }
You need to create a new Pk (I removed the constructors from my original answer for short) and set it in the Sale element. I would do something like this:
Sale sale = new Sale(); Pk pk = new Pk(saleAssistant.getId(), customer.getId(), product.getId()); sale.setPk(pk); sale.setSoldBy(saleAssistant); sale.setBuyer(customer); sale.setProduct(product); ...
And then save the Sale .
Also, in JoinColumn annotations, in which column are the "name" fields indicated? Do pks “target relationships” or sales tables have their own column names?
In the columns for the attributes of a composite Pk (i.e., the sales column proper names tables) we want them to get PK and FK constraints.