postgesql数据库使用hibernate的遇到的一点问题

先抛个错:

ERROR - Exception executing batch: 
org.hibernate.StaleStateException: Batch update returned unexpected row count fr
om update [0]; actual row count: 0; expected: 1

在自己学习项目中使用hibernate的getHibernateTemplate().save(o)方法时遇到了这个错误,看网上说是我对自增长主键赋值了,导致这个问题。实际上我查看了代码,并没有发现我在哪里有对自增主键赋值的过程;后面分析,我需要插入的主表,有分表继承关系,主表中也使用了pg的规则功能来插入分表数据,所以很有可能hibernate无法处理这一层关系,导致插入时报错了。后面我看前辈们写的关于有分表功能的插入语句时,没有采用hibernate的save方法,细细一想,这应该也是前辈绕过了这个坑了。对于这种表结构,如果需要写插入sql,不要采用hibernate的功能,而是自己去写原始sql来插入数据;类似如下

Connection conn = null;
        StringBuffer sql = new StringBuffer();
        sql.append("insert into example_user(id,username,password,nickname,sex,birthday)"+
        "values(");
        sql.append("NEXTVAL('USER_SEQ')");
        sql.append(",?,?,?,?,?)");
        PreparedStatement ps = null;
        try{
            ApplicationContext applicationContext = new FileSystemXmlApplicationContext("classpath:application-context-datasource.xml");
            SessionFactory sessionFactory = (SessionFactory) applicationContext.getBean("sessionFactory");
            ConnectionProvider cp = ((SessionFactoryImplementor)sessionFactory).getConnectionProvider();
            conn = ((LocalDataSourceConnectionProvider)cp).getDataSource().getConnection();
            ps=conn.prepareStatement(sql.toString());
            ps.setString(1,userEntity.getUsername());
            ps.setString(2,userEntity.getPassword());
            ps.setString(3,userEntity.getNickname());
            ps.setInt(4,userEntity.getSex());
            ps.setTimestamp(5,userEntity.getBirthday());
            ps.addBatch();
            ps.executeBatch();
        }catch (SQLException e){
            System.out.println(e.toString());
        }
        finally {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值