问题
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 overwriting fields that aren't in the form with null. But how can I let them set fields in the form to null if they need to?
For example, the user edits an Event
object. Event.date
is 1/1/13. The user sets the Event.date
field in the form to empty and submits the form. Inspecting Event.date
in the debugger shows its value is null. I save the Event
. If I look at the Event
in the database, its value is still 1/1/13.
Edit: It seems there is a method for this. The only problem is it doesn't work on nested entities. Any solutions for this?
update(Object bean,Set<String> properties)
回答1:
Create an ebean.properties
file right next to the application.conf
file and add this line to it:
ebean.defaultUpdateNullProperties=true
回答2:
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<Event> 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<Event> 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.
来源:https://stackoverflow.com/questions/14795220/how-do-i-tell-play-framework-2-and-ebean-to-save-null-fields