首页 > 解决方案 > 使用表键映射一对多

问题描述

我有主桌商户和副桌交易:

商户:

@Entity
@Table
public class Merchants {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private int id;

    @Column(length = 255)
    private String name;

交易:

@Entity
@Table
public class PaymentTransactions {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", updatable = false, nullable = false)
    private int id;

    @Column(length = 4)
    private int reference_transaction_id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "merchant_id")
    private Merchants merchants;

如何将商家 ID(表键)配置为表交易的参考键作为表列merchant_id

标签: javahibernatejpaspring-data-jpa

解决方案


我怀疑您是否应该在 @JoinColumn 注释中使用 referencedColumnName 属性,并将 PaymentTransactions 更改为 List:

@Entity
@Table
public class Merchants {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    @Column(length = 255)
    private String name;

    @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "merchant")
    List<PaymentTransactions> transactions;
}

@Entity
@Table
public class PaymentTransactions {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", updatable = false, nullable = false)
    private int id;

    @Column(length = 4)
    private int reference_transaction_id;

    @ManyToOne
    // here referencedColumnName is id column of merchant entity
    @JoinColumn(name = "merchant_id", referencedColumnName = "id", insertable = false, updatable = false) 
    private Merchants merchant;
}

推荐阅读