In use Hibernate3.05 + Spring1.2 + WebWork2.17 development projects, often encountered an error similar to the following: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [com. hymake.hyplat.acl.impl.Group # 3500]
at org.hibernate.engine.PersistenceContext.checkUniqueness (PersistenceContext.java: 543)
debugging by tracing in, found in the Hibernate Session's EntryByKey exists in another Action layer of the primary key and the same PO ... in fact, that is, Detached state, and then sustained when he met the other when the same PO Hibernate in Action layer error .. my specific code like this: < br> private IUser _user;
public String edit () throws Exception {
_user = _userService.getUser (getKeyID ());< br>}
public String save () throws Exception {
String [] groups = getRequest (). getParameterValues (IGroup group = _groupService.getGroupByName (groups [i]);
/ / because then the _user as detached state, it will be sustained at EntryByKey this _user, but the original _user hashCode different
/ / may wish to call this user1
group.addUser (_user);
_user.addToGroup (group);
}
}
/ / Here, the persistence time of _user found There are other tools in the EntryByKey Identity of the same PO, so Hibernate to error
/ / my side of the user is in addition to the ID with Hibernate, but also the primary key using the business name as equals to judge conditions and the formation of HashCode
/ / side of the _user addition to basic information and the above user1 the same, but in groups of more than a group field.
_userService.saveUser (_user);
}
initial resolution approach is: ① the place plus an _user = _userService.getUser (_user.getName ());< br> for a lasting look again on the user, then OK out of the question .. can, under the user name here ① obtained from the database to a user,
then edit the original page is covered all the things out. Do the assignment again to the user one by one? clearly not feasible.
So what Hibernate example adminApp achieve it? View the source code of his, he is written like this:
public String save () {
User user = getUser ();// here getUser () is equivalent to our above _user
/ / re-associate with the Session
getSession (). update (user);
}
getSession what is it? he was abstractAction is written. We can
WebWork base class in this action Write:
protected Session getHibernateSession () {
if (_sessionFactory == null) {
_sessionFactory = (SessionFactory) getBean (_sessionFactory, true);
}
protected final Object getBean (final String beanName) {
ServletContext servletContext = ServletActionContext
. getServletContext ();
WebApplicationContext wac = WebApplicationContextUtils
. getRequiredWebApplicationContext ( servletContext);
return wac.getBean (beanName);
}
this problem solved ..:)
No comments:
Post a Comment