【发布时间】:2015-06-15 10:25:43
【问题描述】:
我需要在保存之前知道模型对象的某些字段是否已更改,因为我需要将新值与旧值进行比较。
我无法触摸模型类是否已生成。
我的问题是,每当我更改控制器中的对象并检查数据库以在保存修改后的对象之前存储该对象时,从数据库返回的对象与修改后的对象“相同”。
我正在使用 Play! 1.2.7,基本上我有这个:
class MyModel extends Model {
public String label;
}
class MyModels extends Controller {
public static void save(Long id) {
MyModel m = MyModel.findById(id); // at this point m.label is "original"
m.label = "changed !";
MyModel m2 = MyModel.findById(id); // m2.label is "changed !" but should be "original", shouldn't it ?
}
}
也许问题是:如何强制 JPA EntityManager 真正查看数据库而不是从上下文返回对象?因为这似乎是这里真正的问题。
解决方案
所以最终的解决方案是:
class MyModels extends Controller {
public static void save(Long id) {
MyModel m = MyModel.findById(id); // at this point m.label is "original"
m.label = "changed !";
MyModel m2;
JPAPlugin.startTx(false);
try {
m2 = MyModel.findById(id); m2.label is "original"
} finally {
JPAPlugin.closeTx(false);
}
}
}
实现此目的的另一种方法是像这样创建一个新的 EntityManager:
EntityManager manager = JPA.entityManagerFactory.createEntityManager();
// set your new EntityManager as you like...
manager.setProperty("org.hibernate.readOnly", true);
Query q = manager.createQuery("select m from MyModel m where id = :id");
q.setMaxResults(1);
q.setParameter("id", m.getBaseId());
MyModel m2 = (MyModel) q.getResultList().get(0);
【问题讨论】:
-
对象是否实现了 hashCode 函数?
-
我不知道。但是我需要确切知道哪个字段被修改了......
标签: java hibernate jpa playframework playframework-1.x