简体   繁体   中英

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 . But I don't know how to do it using 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:

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM