我有一个Struts 1.3和Hibernate 3.1应用程序,它使用open-session-in-view模式来维护hibernate事务。在对象上执行session.save()之后,在对象中设置了它的标识符,但是在我将对象传递给新的动作类之后,由hibernate管理的所有属性,如对象的标识符被设置为空值。
客户端没有使用Spring,所以我必须编写自己的请求过滤器实现模式,如下所示:
//get a transaction from JTA
transaction = (UserTransaction)new InitialContext().lookup("java:comp/UserTransaction");
transaction.begin();
// Call the next filter (continue request processing)
chain.doFilter(request, response);
// Commit and cleanup
log.finer("Committing the database transaction");
transaction.commit();
我的SaveActionClass调用服务层来持久保存对象及其相关列表(我控制会话的位置)如下所示:
this.saveAddresses(vendor); //saves a persistant set to the database via dao
this.saveExpCodes(vendor, expCodes); //saves a persistant set to the database via dao
this.savePhoneNumbers(vendor); //saves a persistant set to the database via dao
vendor.save(); //saves the vendor object to the database via dao
session.flush();
session.refresh(vendor);
持久化供应商对象后,供应商对象及其所有子对象都具有有效标识符。然后将vendor对象添加到DynActionForm属性,然后转发到ViewActionClass:
dynaActionForm.set(VENDOR_PROPERTY_NAME, vendor);
return actionMapping.findForward(target); //viewvendor
然后在ViewActionClass中,当我获得vendor属性时,所有标识符都设置为null:
Vendor vendor = (Vendor)dynaActionForm.get(VENDOR_PROPERTY_NAME); //vendorid is now null
为什么持久对象在通过dynActionForm中的属性从一个动作类传递到另一个动作类时会丢失其标识符?
答案 0 :(得分:0)
这里的技巧是在getVendor服务方法中放置session.refresh():
public Vendor getVendor(Vendor vendor, Boolean refresh) {
Session session = HibernateUtil.getSession();
session.setFlushMode(FlushMode.MANUAL);
//refreshing the session here before the get call gave me the would still set some properties to null
/*
if(refresh.booleanValue()){
session.refresh(vendor);
}
*/
vendor = vendor.get();
//however putting the refresh here, after the get() call populated the vendor object properly
if(refresh.booleanValue()){
session.refresh(vendor);
}
....
}