查看:
#{form @UserController.editUser()}
<input type="hidden" value=${user?.id} name="user.id">
#{input key:'user.instructions', label: 'Instructions', value: user?.instructions /}
//// Assume the value of the instructions is "Old" (currently in the database) and the user changes it in the view to "New" using the input box
***(input is a tag I created.)***
<div class="form-actions">
<button id="save" type="submit" class="btn btn-primary" name="event" value="update">
<i class="icon-save"></i> Save
</button>
</div>
#{/form}
Controller :
public static void editUser(User user) {
User old = User.findById(user.id);
/// Right here I need the old record before i edit it. How do i get the old value? That is, i need record with user.instructions = "Old". I always get the record where user.instructions = "New" even though it is not saved in the database
user.save();
}
最佳答案
我认为发生这种情况是因为,提交表单后,Play!Framework JPA 对象绑定(bind)会对内存中的数据进行更改(不是数据库中的数据,因为它尚未持久化)。
我已经尝试过这段代码,它对我有用..:) 为了解决这个问题,您的 editUser
Controller 操作可能如下所示:
public static void editUser(User user) {
JPA.em().detach(user); // detach framework managed user object
User old = User.findById(user.id); // get old value from database (get original data)
// in this scope, "old" variable has same value as in database
...
user = JPA.em().merge(user); // tell framework to manage user object again and reassign variable reference
user.save(); // persist change to database
}
<小时/>
This article can be a good reference:
关于java - Play框架在保存之前检索同一对象的旧记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16008197/