java - Play框架在保存之前检索同一对象的旧记录

标签 java database playframework record playframework-1.x

查看:

#{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/

相关文章:

postgresql - 错误 : value seq is not a member of object slick. dbio.DBIO

java - UrlConnection 无内容类型

java - 数组不保存信息

java - 如何将 CompositeKey 复制/分配到 hadoop 中的另一个 CompositeKey?

python - 持续处理来自 PostGres 数据库的数据——采用什么方法?

sql select,获取应有工作的汽车

python - Python 中的蒙特卡罗模拟 : How to get exactly identical transition probabilities from modeled data?

java - <Play!> 从 JPA 中的 <JPABase> 检索唯一生成的 ID

java - PrimeFaces validator 属性方法中的 NPE

java - 获取 mongodb 身份验证失败错误