错误:Illegal attempt to associate a collection with two open sessions

错误: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;
	}
}
究其原因,还不是很清楚。记录下此问题供以后研究,也希望能够为遇到同样问题的朋友们提供一条思路。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值