How do I tell Play Framework 2 and Ebean to save null fields?

后端 未结 2 1841
囚心锁ツ
囚心锁ツ 2021-02-08 01:16

I\'m using Play Framework 2 and Ebean. When a user submits a form to edit an existing object in the database, it doesn\'t save null values. I guess this is to prevent overwrit

2条回答
  •  失恋的感觉
    2021-02-08 01:28

    Null properties in Ebean are considered as unloaded, so to prevent accidental nulling properties that shouldn't be nulled, they are just excluded.

    Because of this reverting Date (and other fields) to null in Ebean is... hard :). Last time when I had to do the same thing (revert Date) I used second query to do just... nulling the Date (after event.update(Object o)):

    public static Result updateEvent(){
        Form eventForm = form(Event.class).bindFromRequest();
    
        // do some validation if required...
    
        Event event = eventForm.get();
        event.update(event.id);
    
        if (eventForm.get().date == null){
           Ebean
             .createUpdate(Event.class, "UPDATE event SET date=null where id=:id")
             .setParameter("id", page.id).execute();  
        }
    
    }
    

    On the other hand, if you are using comparison, for filtering events (always selecting newer than X), you can just set the date to very 'old' value, which also should do the trick. In this case you'll update the object only once.

    private static final Date VERY_OLD_DATE = new GregorianCalendar(1, 0, 1).getTime();
    
    public static Result updateEvent(){
        Form eventForm = form(Event.class).bindFromRequest();
        Event event = eventForm.get();
        if (eventForm.get().date == null){
            event.date = VERY_OLD_DATE;
        }
    
        event.update(event.id);
    }
    

    In this case in your HTML form you will need to clear the value of the form's field (or just send every time date like 0001-01-01), however it can be done easily even with JavaScript.

提交回复
热议问题