2012-02-29 58 views
0

在我play1.2.4的應用程序,我有一個Customer誰可以有SetPaymentMethod一個s.I試圖像下面的模型,並且還寫在控制器方法的付款方法添加到Customer.payments。playframework模型不保存正確

但是,這些方法給出了奇怪的結果。當添加付款時,customer.payments集合正確顯示爲增加1個元素。然後,當我轉到另一個控制器方法以顯示客戶的paymentMethods時,它表示customer.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字段應該有針對客戶的數字,但empty.It似乎customer.save()控制器沒有犯..

這究竟是爲什麼?有人可以告訴嗎?..任何幫助表示讚賞。

+0

什麼findOrCreateNewPayment看起來不一樣? – digiarnie 2012-02-29 07:37:36

+0

我用添加的方法編輯了問題 – 2012-02-29 08:21:35

回答

1

當您創建新的PaymentMethod時,客戶在保存之前是否設置了對象?因此,像這樣:

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

此外,如果你希望一個客戶與付款方法有關,你可能想使客戶字段不能爲空:

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

我必須明確地設置PaymentMethod上的客戶嗎?我以爲cascade = ALL會照顧 – 2012-02-29 07:51:07

+0

我認爲,因爲您在實體類中具有雙向關係將不得不。請參閱:http://docs.jboss.org/hibernate/core/4.0/manual/en-US/html/tutorial.html#tutorial-associations-usingbidir – digiarnie 2012-02-29 08:10:01

+0

感謝@digiarnie指出我的代碼中的缺陷 – 2012-02-29 08:34:16