日期:2014-05-20  浏览次数:20671 次

hibernate事务的问题
我用myelipse反向生成了数据库表的对象。所以代码里面有挺多像findByXXX的方法调用。

现在问题来了,由于前台随时会发送请求,所以数据有时数据就会出现重复,我想问题是这样的。
Java code

        Byte mainsrv = as.getIsDomainSrv();
        List<AccessServer> serverList = serverDao.findAll();
        if(serverList != null){
            for(AccessServer server : serverList){
                if(server.getServerIp().equals(as.getServerIp())){
                    System.out.println("要添加的服务器已存在");
                    oplogmgr.add(as.getServerIp(), 21, 1, as.getServerName(), 10);
                    return -10;   //返回一个特殊类型的错误代码
                }
                if ( (mainsrv.intValue() == 1) && (server.getIsDomainSrv().intValue() == 1) ){
                    System.out.println("已经存在主服务器");
                    oplogmgr.add(as.getServerIp(), 21, 1, as.getServerName(), 11);
                    return -11;
                }
                
            }
        }
        if (mainsrv.intValue() == 0 && countSelectServer().compareTo(getUkeyServerNumber()) >= 0) {
            System.out.println("ukey限制添加服务器");
            oplogmgr.add(as.getServerIp(), 21, 1, null, ErrorCode.UKEYDENEY);
            return ErrorCode.UKEYDENEY;
        }
        Session session=null;
        Transaction tx=null;
        try{
            session = serverDao.getSessionFactory().openSession();
            tx=session.beginTransaction();
            session.save(as);
            tx.commit();
        }
        catch (RuntimeException e) {
            e.printStackTrace();
            if (tx != null){
                tx.rollback();
            }
                }
        finally{
            if(session!=null){
                session.close();
            }
        }
        oplogmgr.add(as.getServerIp(), 21, 1, as.getServerName(), 0);



假如一个请求要求添加ip地址为192.168.1.5的服务器,当在提交之前又有一个请求进来,也是要求添加192.168.1.5,
第一个请求在执行tx.commit();之前如果第二个请求就执行到serverDao.findAll();那就会添加两个ip地址一样的服务器,这是我不想要的。
有没有什么办法可以在openSession之后不允许在读写?

------解决方案--------------------
悲观锁~
------解决方案--------------------
你可以在<property />标签上设置unique='true'这样当另一个请求也插入相同的数据的话,由于该字段不能重复,会抛出异常,事务会回滚,插入失败
------解决方案--------------------
在<property/>标签上设置unique='true'试试,这样该字段不允许重复
------解决方案--------------------
学习