首页 > 解决方案 > 使用重复的额外列使多对多休眠

问题描述

所以我想在多对多的情况下设置一个带有附加属性的表。

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”添加到主键或仅将日期转换为主键?

标签: springdatabasespring-boothibernate

解决方案


由于复杂的 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{

推荐阅读