我正在进行结帐,当用户去购物时,会创建一个Purchase
对象并将其保存到数据库中。然后,我获取对象的id
并将其发送给PayPal以生成一个按钮(这样以后我就可以识别购买了)。但是,当我尝试检索id时,它返回null。
在访问ID之前,我尝试过刷新它,但是它似乎仍然无法正常工作。
这是我的域对象:
package website
import java.time.Instant
import java.time.temporal.ChronoUnit
class Purchase {
String buttonId
final Instant expires
private boolean complete
User user
Product product
Purchase(Product product, User user) {
this.product = product
this.user = user
expires = Instant.now().plus(1, ChronoUnit.DAYS)
}
void completePurchase() {
// confirm that the purchase hasn't been completed already
if (complete) {
throw new PurchaseAlreadyCompleteException()
}
complete = true
}
boolean isComplete() {
return complete
}
static class ButtonIdAlreadyInitializedException extends RuntimeException {}
static class PurchaseAlreadyCompleteException extends RuntimeException {}
}
Purchase purchase = new Purchase(product, user)
purchase.save(flush: true)
println 'purchase id: ' + purchase.id
最佳答案
该ID为null,因为未保存您的对象。之所以不被保存,是因为您没有为buttonId
分配值,并且此属性是必需的。您可以使用以下方法进行验证:
Purchase purchase = new Purchase(product, user)
purchase.save(flush: true, failOnError: true) // will throw an exception if saving fails
println 'purchase id: ' + purchase.id
https://stackoverflow.com/questions/39215071/