Hibernate批量添加与更新

	/**
	 * 批量insertIDMC表
	 * @param entityType
	 * @return
	 */
	public OperationResult batchInsert(final List id2Names){
		if(id2Names != null && id2Names.size() > 0){
			this.getSession().doWork(new Work() {
				@Override
				public void execute(Connection connection) throws SQLException {
					String sql = "insert into entity_id_name (entitytypeid,entityid,entityname,tenantId) values (?,?,?,?)";
					final PreparedStatement stmt = connection.prepareStatement(sql);
					for (final EntityIdName idName : id2Names) {
						stmt.setLong(1, idName.getEntityTypeId());
						stmt.setLong(2, idName.getEntityId());
						stmt.setString(3, idName.getEntityName());
						stmt.setLong(4, idName.getTenantId());
						stmt.addBatch();
					}
					log.info("开始批量执行"+id2Names.size()+"条SQL语句["+sql+"]...");
					Long t1 = System.currentTimeMillis();
					stmt.executeBatch();
					Long t2 = System.currentTimeMillis();
					log.info("执行完毕,共耗时:" + (t2-t1) + "毫秒");
				}
			});
		}
		return OperationResult.SUCESS;
	}
	
	/**
	 * 批量insertIDMC表
	 * @param entityType
	 * @return
	 */
	public OperationResult batchUpdate(final List id2Names){
		if(id2Names != null && id2Names.size() > 0){
			this.getSession().doWork(new Work() {
				@Override
				public void execute(Connection connection) throws SQLException {
					String sql = "UPDATE entity_id_name SET entityname = ? WHERE entitytypeid = ? AND entityid = ?";
					final PreparedStatement stmt = connection.prepareStatement(sql);
					for (final EntityIdName idName : id2Names) {
						stmt.setString(1, idName.getEntityName());
						stmt.setLong(2, idName.getEntityTypeId());
						stmt.setLong(3, idName.getEntityId());
						stmt.addBatch();
					}
					log.info("开始批量执行"+id2Names.size()+"条SQL语句["+sql+"]...");
					Long t1 = System.currentTimeMillis();
					stmt.executeBatch();
					Long t2 = System.currentTimeMillis();
					log.info("执行完毕,共耗时:" + (t2-t1) + "毫秒");
				}
			});
			
		}
		return OperationResult.SUCESS;
	}


 
 

你可能感兴趣的:(Hibernate)