错误:Illegal attempt to associate a collection with two open sessions
我的dao层delete方法代码:
/**
* 删除用户
*
* @param userIdAry
* @return 删除的用户名
*/
public String deleteUser(String userIdAry) {
System.out.println("method is run");
String[] userIds = userIdAry.split(",");
Long[] ids = new Long[userIds.length - 1];
if (userIdAry != null) {
for (int i = 0; i < userIds.length; i++) {
if (userIds[i] != null && !"".equals(userIds[i])) {
ids[i - 1] = Long.valueOf(userIds[i]);
}
}
}
String usernameAry = "";
for (int i = 0; i < ids.length; i++) {
User user = get(ids[i]);
if (i == 0) {
usernameAry = user.getUsername();
} else {
usernameAry += "," + user.getUsername();
}
remove(user);
}
System.out.println("usernameAry:" + usernameAry);
return usernameAry;
}
用上面方法删除单个或多个用户会报不能同时连接2个打开的session,而我的web.xml中是要求只能用一个session:
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>
后来我看了一下GenericDaoHibernate中的公共方法中有2个remove方法:
/**
* {@inheritDoc}
*/
public void remove(T object) {
Session sess = getSession();
Transaction tx = sess.beginTransaction();
sess.delete(object);
tx.commit();
// sess.delete(object);
}
/**
* {@inheritDoc}
*/
public void remove(PK id) {
Session sess = getSession();
Transaction tx = sess.beginTransaction();
IdentifierLoadAccess byId = sess.byId(persistentClass);
T entity = (T) byId.load(id);
sess.delete(entity);
tx.commit();
}
我在想,会不会是User user=get(ids[i]);会不会这里打开了另一条session?
最后我将delete方法改成如下就可以了:
/**
* 删除用户
*
* @param userIdAry
* @return 删除的用户名
*/
public String deleteUser(String userIdAry) {
System.out.println("method is run");
String[] userIds = userIdAry.split(",");
Long[] ids = new Long[userIds.length - 1];
if (userIdAry != null) {
for (int i = 0; i < userIds.length; i++) {
if (userIds[i] != null && !"".equals(userIds[i])) {
ids[i - 1] = Long.valueOf(userIds[i]);
}
}
}
String usernameAry = "";
for (int i = 0; i < ids.length; i++) {
String username = get(ids[i]).getUsername();//这里由User类型换成了String类型
if (i == 0) {
usernameAry = username;
} else {
usernameAry += "," + username;
}
remove(ids[i]);//这里改成根据id来删除用户
}
System.out.println("usernameAry:" + usernameAry);
return usernameAry;
}
}
究其原因,还不是很清楚。记录下此问题供以后研究,也希望能够为遇到同样问题的朋友们提供一条思路。