[英]Playframework: how to decide if insert or update based on a field
I want to save form record when amount
equals to 0
and update it when amount > 0
. 我想在
amount
等于0
时保存表单记录,并在amount > 0
时更新它。 But I don't know how to do it using Playframework. 但是我不知道如何使用Playframework做到这一点。 Here is my code:
这是我的代码:
Controllers method: 控制器方法:
public static Result add() {
Form<Store> taskData = form(Store.class);
Form<Store> tasks = taskData.bindFromRequest();
Store.recharge(tasks.get());
return ok ("Stored successfully");
}
Models: 楷模:
@Entity
@Table(name = "store")
public class Store extends Model {
@Id
public Long id;
public int amount;
public static Finder<Long, Store> find = new Finder(Long.class, Store.class);
public static List<Store> all() {
return find.all();
}
public static Store findById(Long id) {return (find.ref(id));}
public static void add (Store data) {
data.save();
}
}
It seems like you may not be using the Form functionality correctly, here's a complete working example: 看来您可能没有正确使用Form功能,这是一个完整的工作示例:
Route 路线
POST /test @controllers.Application.test()
Controller: 控制器:
public Result test() {
Form<Store> storeForm = Form.form(Store.class);
Store store = storeForm.bindFromRequest().get();
System.out.println(Json.toJson(store));
if (store.getAmount() > 0) {
//update
System.out.println("perform update");
} else {
//save or recharge
System.out.println("perform recharge");
}
return ok();
}
Model 模型
public class Store {
private Long id;
private int amount;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
}
request: 请求:
curl -X POST -H "Cache-Control: no-cache" -H "Content-Type: application/x-www-form-urlencoded" -d 'id=12345&amount=0' "http://localhost:9000/test"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.