model driven 更新实体 外键集合丢失问题
在使用ssh框架开发web的时候,有的时候使用model driven方式接收参数,在通常情况下没有什么问题。当执行更新操作的时候,由于执行update的时候,实体的外键关系,容易被删除掉,这个问题需要注意。例如
有用户表User和用户组表UserGroup
User(id,name,userGroupId)
UserGroup(id,name)
public class UserGroup {private int id;private String name;private List<User> user;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}@OneToMany(fetch=FetchType.LAZY,mappedBy="userGroup")public List<User> getUser() {return user;}public void setUser(List<User> user) {this.user = user;}}
public class User {private int id;private String name;private UserGroup userGroup;@Id@GeneratedValuepublic int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}@ManyToOne(fetch=FetchType.LAZY)@JoinColumn(name="userGroupId")public UserGroup getUserGroup() {return userGroup;}public void setUserGroup(UserGroup userGroup) {this.userGroup = userGroup;}}
@Componentpublic class BaseDao extends HibernateDaoSupport{@Resource(name="sessionFactory")public void setHibernateTemplate(SessionFactory sessionFactory) {super.setSessionFactory(sessionFactory);}public boolean update(Object obj){boolean result = false;try { //根据主键加载对应实体Object dbObj = getHibernateTemplate().get(obj.getClass(), Integer.parseInt(obj.getClass().getDeclaredMethod("getId").invoke(obj, new Object[]{}).toString()));Method[] allMethod = obj.getClass().getDeclaredMethods(); Map<String, Method> allGetMethod = new HashMap<String, Method>();Map<String, Method> allSetMethod = new HashMap<String, Method>();for(int i = 0; i < allMethod.length; i++){Method method = allMethod[i];if(method.getName().startsWith("get")){allGetMethod.put(method.getName().substring(3), method);}else if(method.getName().startsWith("set")){allSetMethod.put(method.getName().substring(3), method);}} //将model driven的实体属性赋值给从数据库载入的实体(List、Set属性除去)for(int i = 0; i < allMethod.length; i++){Method method = allMethod[i];if(method.getName().startsWith("set")){Class[] paraType = method.getParameterTypes();if(paraType.length > 0){if(paraType[0] != List.class && paraType[0] != Set.class){method.invoke(dbObj, new Object[]{allGetMethod.get(method.getName().substring(3)).invoke(obj, new Object[]{})});}}}}getHibernateTemplate().update(dbObj);} catch (DataAccessException e) {e.printStackTrace();} catch (IllegalArgumentException e) {e.printStackTrace();} catch (SecurityException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();} catch (InvocationTargetException e) {e.printStackTrace();} catch (NoSuchMethodException e) {e.printStackTrace();}return result;}}