gpt4 book ai didi

java - Playframework:如何根据字段决定是否插入或更新

转载 作者:行者123 更新时间:2023-11-29 21:03:56 25 4
gpt4 key购买 nike

我想在amount等于0时保存表单记录,并在amount > 0时更新它。但我不知道如何使用 Playframework 来做到这一点。这是我的代码:

Controller 方法:

public static Result add() {
Form<Store> taskData = form(Store.class);
Form<Store> tasks = taskData.bindFromRequest();
Store.recharge(tasks.get());
return ok ("Stored successfully");
}

型号:

@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();
}
}

最佳答案

看来您可能没有正确使用表单功能,这是一个完整的工作示例:

路线

    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();
}

型号

    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;
}
}

请求:

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"

关于java - Playframework:如何根据字段决定是否插入或更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36984427/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com