我想知道在Java上使用HB更新一个脱离对象的某些字段的最佳方法是什么.特别是当对象具有子对象属性时.例如(删除注释并减少字段数以减少噪音):
public class Parent {
int id;
String field2;
...
Child child;
}
public class Child {
int id;
String field3;
}
Run Code Online (Sandbox Code Playgroud)
在MVC webapp中更新Parent时,我可以使用Session.get(Parent.class,123)调用父实例,使用它来填充表单并显示它.没有DTO,只有被释放的父级传递给视图并绑定到表单.现在,我只想让用户更新父级的field2属性.因此,当用户发布表单时,我得到一个父实例,其中id和field2已填充(我认为mvc框架在这里不重要,绑定时所有行为大致相同).
现在,哪种策略最适合执行实体更新?我可以考虑一些替代方案,但我想听听专家:)(请记住,我不想放松父实例和子实例之间的关系)
A)再次从Session中重新获取Parent实例,并手动替换更新的字段
Parent pojoParent; //binded with the data of the Form.
Parent entity = Session.get(Parent.class,pojoParent.getId());
entity.setField2(pojoParent.getField2()).
Run Code Online (Sandbox Code Playgroud)
我经常使用它.但pojoParent似乎被用作卧底DTO.如果要更新的字段数量变大,那也很糟糕.
B)将Child存储在某处(httpSession?)并将其关联到后者.
Parent parent = Session.get(Parent.class,123);
//bind the retrieved parent to the form
// store the Child from parent.getChild() on the httpSession
...
//when the users submits the form...
pojoParent.setChild(someHttpSessionContext.getAttribute('Child'))
Session.save(pojoParent);
Run Code Online (Sandbox Code Playgroud)
我认为这是垃圾,但我在一些项目中看到了......
C)将Parent和Child之间的关系设置为不可变.在关系上使用 …
我看到了更新操作的类型:第一:
getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session) {
session.flush();
session.setCacheMode(CacheMode.IGNORE);
SomeObject ss = (SomeObject) session.get(SomeObject.class, id);
long next = ss.getAndIncrement();
session.update(ss);
session.flush();
return null;
}
});
Run Code Online (Sandbox Code Playgroud)
其次
SomeObject ss = loadSomeObject();
long next = ss.getAndIncrement();
getHibernateTemplate.merge(ss);
Run Code Online (Sandbox Code Playgroud)
这两种方法也是一样的.我想知道哪一个更好,更安全,为什么.谢谢.