从bean获取唯一的实体ID

时间:2019-03-07 21:27:10

标签: java jpa

我有2个实体:

    @Entity
    @Table(name = "wpf_payment_attributes")
    public class WpfPaymentAttributes implements Serializable {

        private static final long serialVersionUID = -2629784870868584850L;

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

        @Column(length = 32)
        private Integer wpf_payment_id;

        @Column(length = 255)
        private String name;
        ....
}

第二个实体:

@Entity
@Table(name = "wpf_payments")
public class WpfPayments implements Serializable {

    private static final long serialVersionUID = -5740164339503774805L;

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

    @Column(length = 4)
    private Integer merchant_id;
    .....
}

id由数据库生成。我使用以下代码插入一些数据:

WpfPayments obj = new WpfPayments();
 obj.setReference_transaction_id(12345678);
 obj.setContract_id(contract.getId());
 obj.setMerchant_id(merchant.getId()); 
 wpfPaymentsService.saveOrUpdate(obj);

 WpfPaymentAttributes attibutes = new WpfPaymentAttributes();
 attibutes.setName("usage");
 attibutes.setValue("Test Usage");
 attibutes.setWpf_payment_id(...get here some how WpfPayments table id...id);

 wpfPaymentAttributesService.saveOrUpdate(attibutes);

您知道如何从WpfPayments对象获取ID并使用attibutes.setWpf_payment_id(...)保存吗?

1 个答案:

答案 0 :(得分:0)

您应将JoinTable属性与该实体的设置器一起使用,而不要使用WpfPayments的ID。 一旦在该实体的存储库上调用save方法,就生成WpfPayments的ID,只需使用它的结果即可。