Q1. How can we model a ternary relationship using Hibernate? For example, how can we model the ternary relationship presented here using Hibernate (or JPA)? (…)
我会改造与中间实体类的关联(这是Hibernate的推荐方法).适用于您的示例:
@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) { ... }
// getters, setters, equals, hashCode
}
@EmbeddedId
private Pk pk;
@ManyToOne
@JoinColumn(name = "SOLDBYID", insertable = false, updatable = false)
private SaleAssistant soldBy;
@ManyToOne
@JoinColumn(name = "BUYERID", insertable = false, updatable = false)
private Customer buyer;
@ManyToOne
@JoinColumn(name = "PRODUCTID", insertable = false, updatable = false)
private Product product;
// getters, setters, equals, hashCode
}
Q1.1. How can we model this variation, in which each Sale item might have many Products?
我不会在这里使用复合主键并为Sale实体引入PK.
Q2. In general, how can we model n-ary, n >= 3 relationships with Hibernate?
我认为我对Q1的回答.涵盖了这个.如果没有,请澄清.
更新:回答OP的评论
(…) the pk’s fields are not getting populated and as a result I cannot save Sale items in the DB. Should I use setters like this for the Sale class? public void setBuyer(Customer cust) { this.buyer = cust; this.pk.buyerId = cust.getId(); }
您需要创建一个新的Pk(我从原始答案中删除了构造函数以获得简洁性)并将其设置在Sale项目上.我会做这样的事情:
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);
...
然后坚持销售.
Also, in the JoinColumn annotations, what column are “name” fields referring to? The target relations’ pks or the sale table’s own column names?
对于复合Pk属性的列(即销售表自己的列名),我们希望它们获得PK和FK约束.