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

时间:2016-05-02 14:05:28

标签: java mysql playframework

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

控制器方法:

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

1 个答案:

答案 0 :(得分:0)

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

路线

    POST    /test  @controllers.Application.test()      

控制器:

    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"