簡體   English   中英

Playframework:如何根據字段決定是插入還是更新

[英]Playframework: how to decide if insert or update based on a field

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

看來您可能沒有正確使用Form功能,這是一個完整的工作示例:

路線

    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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM