开发者社区> 问答> 正文

同一service里使用Hibernate和jdbc操作数据库

jdbc操作后hibernate无法读取到插入的数据,经断点测试确实已经保存到数据库

service稍微改了一些业务内的东西,抱歉

public void addXXX(){
        // amount 
        String xxxHQL = " from XXX as rr where aaId=? and bbId=?";
        String yyyHQL = " from YYY as cr where aaId=? and bbId=?";
        long xxxCount = 0;
        long yyyCount = 0;
        // batch add sql
        String sql = "insert into XXX(--,--,--,--,--,--) value(?,?,?,?,?,?)";
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
 
        connection = dataSource.getConnection();
        connection.setAutoCommit(false);
        preparedStatement = connection.prepareStatement(sql);
             
        for () {
 
            preparedStatement.setInt(1, );
            preparedStatement.setInt(2, );
            preparedStatement.setInt(3, );
            preparedStatement.setInt(4, );
            preparedStatement.setTimestamp(5, );
            preparedStatement.setString(6, );
            preparedStatement.addBatch();
 
        }
        preparedStatement.executeBatch();
        preparedStatement.close();
        connection.commit();
     
        } catch (Exception e) {
            try {
                connection.rollback();
                connection.close();
            } catch (SQLException e1) {
            }
            e.printStackTrace();
        } finally {
            try {
                connection.close();
            } catch (SQLException e) {
            }
        }
        xxxDao.getCurrentSession.clear();
        for () {
            xxxCount = xxxDAO.getSum(xxxHQL);// @Autowired注入
            yyyCount = yyydDAO.getCount(yyyHQL);// @Autowired注入
            // xxxCount 无法读取hibernate插入数据
        }
    }

展开
收起
a123456678 2016-03-17 09:34:34 1806 0
1 条回答
写回答
取消 提交回答
  • 上面的代码简化如下:

    connection 1 打开,connection 1 开启事务

    connection 2 打开,connection 2 开启事务,connection 2提交,connection 2关闭。

    connection 1 查询, connection 1 提交事务,connection 1 关闭。

    你觉得connecton 2 跟connection 是一个事务里面的? 显然不是。

    2019-07-17 19:04:30
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
2022 DTCC-阿里云一站式数据库上云最佳实践 立即下载
云时代的数据库技术趋势 立即下载
超大型金融机构国产数据库全面迁移成功实践 立即下载