使用表键一对多映射

时间:2018-08-11 19:27:22

标签: java hibernate jpa spring-data-jpa

我有主桌商人和第二桌交易:

商人:

@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中表交易的参考密钥?

1 个答案:

答案 0 :(得分:0)

我怀疑您应该在@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;
}