spring - 使用重复的额外列使多对多休眠
问题描述
所以我想在多对多的情况下设置一个带有附加属性的表。
public class Customer {
private int id;
// other attributes
// constructors
// getters / setters
}
public class Product {
private int id;
// other attributes
// constructors
// getters / setters
}
然后我有“访问”类链接前两个
@Entity
@EntityListeners(AuditingEntityListener.class)
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
public class Visit {
@EmbeddedId
private VisitId visitId = new VisitId();
@ManyToOne
@MapsId("customerId")
@JoinColumn(name = "id_customer", nullable = false)
private Customer customer;
@ManyToOne
@MapsId("productId")
@JoinColumn(name = "id_product", nullable = false)
private Product product;
private LocalDateTime date = LocalDateTime.now();
@Embeddable
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public static class VisitId implements Serializable {
private static final long serialVersionUID = 1L;
private int customerId;
private int productId;
}
}
测试客户 1 与产品 1 客户 2 与产品 1
并将其添加到数据库中。但是,如果我在日期不同时尝试再次将客户 1 与产品 1 添加,则它不起作用,因为主键是 CustomerId 和 ProductId。如何将另一个“private int id”添加到主键或仅将日期转换为主键?
解决方案
由于复杂的 ID(客户和产品)不是唯一的,您可以只拥有一个简单的 ID 以及与您指定的表的关系。
@Id
private int visitId
@ManyToOne
@JoinColumn(name = "id_customer", nullable = false)
private Customer customer;
@ManyToOne
@JoinColumn(name = "id_product", nullable = false)
private Product product;
并且可能添加一个独特的约束
@Table(
uniqueConstraints=
@UniqueConstraint(columnNames={"id_customer", "id_product", date })
)
@Entity
public class Visit{
推荐阅读
- javascript - Google Drive Picker API - 显示文件夹和某些 mime 类型文件
- python - 缺少工具社区版与专业版 Pycharm
- reactjs - 如何在子对话框打开后关闭父对话框,使用 Material UI React
- r - 如何删除R中文件的最后一位?
- python - 从网页中解析出文本
- docker - Google App Engine 日志“找不到指定的框架‘Microsoft.AspNetCore.App’,版本‘2.1.1’。”
- sql - 如何设计表以允许在一行上进行多字段查询
- c# - 在 .net 4.5 中的 web.config 中覆盖 Machine.config 的值
- ruby - 如何将 Bugsnag 通知发送到 stderr?
- tensorboard - 将 TensorBoard 与 Keras Tuner 一起使用