先抛个错:
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();
}
}
}