[英]Play framework Retrieve old record of the same object before saving
查看:
#{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}
控制器:
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對象綁定對內存上的數據(而不是數據庫上的數據,因為尚未持久化)進行了更改。
我嘗試了這段代碼,它對我editUser
.. :)為了克服這個問題,您的editUser
控制器操作可能如下所示:
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
}
本文可以作為很好的參考:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.