日期:2014-05-16  浏览次数:20472 次

spring hibernate 批量插入jdbc及hibernate方法
项目中需要用到批量添加,考虑到新能问题用jdbc实现.
记录下来,以后会用.
public void createRolePermissionBySql(final String roleId,final String[] permIds){
		
		getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				if(permIds==null||permIds.length==0)
					      return null;
				Connection conn=session.connection();
				PreparedStatement ps=null;
				String sql=" insert into base_role_permission (ROLE_PERM_ID,PERM_ID,ROLE_ID,CREATE_DATE)" +
						   " values (?,?,?,?) ";
				ps=conn.prepareStatement(sql);
				if(log.isDebugEnabled())
					   log.debug("batch add base_role_permission:"+sql);
				UUIDHexGenerator uuidGenerator=null;
				for(String permId:permIds){
					uuidGenerator=new UUIDHexGenerator();
					ps.setString(1,uuidGenerator.generate(null, null).toString());
					ps.setString(2,permId);
					ps.setString(3, roleId);
					ps.setDate(4, DateUtils.getJavaSqlDate());
					ps.addBatch();
				}
				int[] counts=ps.executeBatch();
				ps.close();
				session.flush();
				session.close();
				return null;
			}
		});
	}
   


hibernate批量插入
public void batchSaveCardDetail(List<TCardInfo> cardDetails) {
        return this.getHibernateTemplate().execute(new HibernateCallback() {
            @Override
            public Object doInHibernate(Session session) throws HibernateException, SQLException {                
		for (int i = 0; i < cardDetails.size(); i++) {
                    session.save(cardDetails.get(i));		
                    if (i % 50 == 0) {
                        session.flush();
                        session.clear();
                    }
                }                
                return null;
            }
        });
}



1 楼 ml365 2010-12-24  
为什么用jdbc批量操作会比hibernate方法效率更好呢?