playframework模型未正确保存

时间:2012-02-29 07:19:11

标签: java playframework

在我的play1.2.4应用中,我有一个Customer可以Set PaymentMethod我尝试对其进行建模,如下所示,并在控制器中编写方法将PaymentMethod添加到Customer.payments。

然而,这些方法给出了奇怪的结果。当添加付款时,customer.payments集正确显示为增加1个元素。然后,当我转到另一个控制器方法来显示客户的paymentMethods时,它说客户.payments是空的。

我无法弄清楚为什么会发生这种情况。有人可以帮助我纠正这个问题吗?

Customer.java:

@Entity
class Customer extends Model{
   ...
   @OneToMany(mappedBy="customer",cascade=CascadeType.ALL)
    public Set<PaymentMethod> payments;

    public Customer(){
      ...
      payments = new HashSet<PaymentMethod>();
    }

}

PaymentMethod.java

@Entity
class PaymentMethod  extends Model{
    ...
    @ManyToOne
    public Customer customer;
}

控制器方法

public static void addNewPaymentMethod(Long custId,...){
    Customer customer = Customer.findById(custId);
    PaymentMethod payment = findOrCreateNewPayment(...);//if already in db get it or create a new one
    customer.payments.add(payment);
    customer.save();
    System.out.println("customer  has:"+customer.payments.size()+" payments");
    showPaymentForm(custId);
}

//此处控制台输出为: 客户有:1笔付款

编辑:findOrCreateNewPayment方法是:

PaymentMethod findOrCreateNewPayment(Customer customer,String paymentNumber,...){
    String query = "select distinct p from PaymentMethod p where p.customer=:customer and and p.paymentNumber=:paymentNumber...";//other fields omitted for brevity
    PaymentMethod payment = PaymentMethod.find(query).bind("customer", customer).bind("paymentNumber", paymentNumber)...first();//other bind params omitted for brevity
    if(payment == null){
      payment = new PaymentMethod(paymentNumber,month,name,day,type);
      payment.save();
    }
    return payment;
}

然而,showPaymentForm()告诉我客户没有任何付款

showPaymentForm(Long custId){
    Customer customer = Customer.findById(custId);
    System.out.println("showPaymentForm():: customer has ="+customer.payments.size()+" payments");
    ...
    render(customer);

}

控制台输出是:

客户有:0付款

另外,当我查看付款表时,我发现了

* id | paymenttype | paymentnumber |月|名字|一年| CUSTOMER_ID *

28 | PayMethod1 | 1111XXXXXX2222 | 11 | jon | 2027年|

此表中的customer_id字段应该有一个客户编号,但是为空。似乎控制器中的customer.save()没有提交..

为什么会这样?有人能说出来吗......任何帮助都表示赞赏。

1 个答案:

答案 0 :(得分:1)

当您创建新的PaymentMethod时,客户是否在保存之前设置了对象?所以像这样:

Customer someCustomer = ...
new PaymentMethod(someType, someNumber, someMonth, someName, someYear, someCustomer).save();

此外,如果您希望客户与PaymentMethod相关联,您可能希望使客户字段不可为空:

@Entity
public class PaymentMethod  extends Model {
    ...
    @Column(nullable = false)
    @ManyToOne
    public Customer customer;
}