保存对象时,在刷新之前保存瞬态实例

时间:2017-09-22 10:11:28

标签: spring-boot spring-data-jpa

我正在尝试保存MotoPayment对象。但在保存motopayment对象之前,我必须检查客户是否存在代码。

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        tabContainer.Items.Add(new MyUserControl());
    }

    private void Button_Click_2(object sender, RoutedEventArgs e)
    {
        Button button = sender as Button;
        tabContainer.Items.Remove(button.Tag);
    }
}

控制器方法

public class MotoPaymentOrder extends BaseDocument {

    @ManyToOne
    @JoinColumn(name = "CUSTOMER")
    private Customer customer;

    @Column(name = "AMOUNT")
    private Double amount = Double.valueOf(0);

    @ManyToOne
    @JoinColumn(name = "PAYMENTSTATUS")
    protected SystemTypeLookupData status ;

    @Column(name = "PNRNO")
    private String pnrNo;

    @Column(name = "RESERVATIONNO")
    private String reservationNo;

}

以下方法用于检查客户是否存在代码,否则保存客户对象。

@RequestMapping(value = "/motopaymnetorder", method = RequestMethod.POST)
    @ResponseBody public MotoPaymentOrder create(@RequestBody MotoPaymentOrder domain){
        prepareCustomer(domain.getCustomer());
        return (MotoPaymentOrder) baseDocumentService.saveDocument(domain);
    }

我在保存MotoPaymentOrder对象时遇到异常:

public void prepareCustomer(Customer customer){
        Customer existingCustomer = (Customer) appService.findOneWhere("WHERE o.code = '"+customer.getCode()+"'",Customer.class);
        if(existingCustomer==null){
            customer.setType(ApplicationConstants.CustomerType.Person);

            PersonCustomer personCustomer = new PersonCustomer();
            personCustomer.setEmail(customer.getCustomerEmail());
            personCustomer.setFirstName(customer.getPersonCustomer().getFirstName());
            personCustomer.setLastName(customer.getPersonCustomer().getLastName());
            personCustomer.setCustomer(customer);

            customer.setPersonCustomer(personCustomer);


        }
    }

2 个答案:

答案 0 :(得分:1)

假设对于MotoPaymentOrder,关联的Customer未被保留,JPA将保留它,这不是您的方法实现的。您可以使用CascadeType.REFRESH告诉hibernate如何处理您的实体,如果该实体尚未保留。

@ManyToOne(cascade=CascadeType.REFRESH)
@JoinColumn(name = "CUSTOMER")
private Customer customer;

答案 1 :(得分:0)

在这里看到 save the transient instance before flushing in SpringBoot 2.0.4 app

@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name = "CUSTOMER")
private Customer customer;