java ary是什么_java – Hibernate中的三元(和n-ary)关系

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约束.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值