1

看法 :

#{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();                           

}
4

1 回答 1

0

我认为这是因为在提交表单后,Play!Framework JPA 对象绑定对内存上的数据进行了更改(不是数据库上的数据,因为它没有被持久化)。

我已经尝试过这段代码,它对我有用.. :) 要克服这个问题,您的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
}

这篇文章可以作为一个很好的参考:

于 2013-04-16T13:49:49.560 回答