基于JPA的工具类 遍历整表数据进行数据清洗DTL
工具类
/*** 作者:guoyzh* 时间:2023/4/4 0004 13:43:16* 功能:数据库批量操作工具*/
@Component
public class SQLDataBatchUtils {@Resourceprivate EntityManager entityManager;/*** 作者:guoyzh* 时间:2023/4/4 0004 14:16:51* 功能:批量对某张表整表进行数据同步操作 从id为0的数据开始查 每次查询500条数据*/public <T> void batchOperator(Class<T> entityClazz, Consumer<List<T>> consumer) {Table tableInfo = entityClazz.getDeclaredAnnotation(Table.class);Optional.ofNullable(tableInfo).map(Table::name).ifPresent(tableName -> {Integer beginId = 0;List<T> datas;do {String sqlStr = StrUtil.format("select * from {} where id > :beginId limit 500", tableName);Query nativeQuery = entityManager.createNativeQuery(sqlStr, entityClazz);nativeQuery.setParameter("beginId", beginId);datas = nativeQuery.getResultList();if (ObjectUtil.isNotEmpty(datas)) {// 记录此次处理的最大id 作为下次查询的起始idT latestItems = datas.get(datas.size() - 1);beginId = Optional.ofNullable(ReflectUtil.getFieldValue(latestItems, "id")).map(Object::toString).map(Integer::parseInt).orElse(0);consumer.accept(datas);Console.log("==============beginId:{}", beginId);}} while (ObjectUtil.isNotEmpty(datas));});}
}
使用方式
SpringUtil.getBean(SQLDataBatchUtils.class).batchOperator(SpreadChannel.class, dataLists -> {});
数据清洗过程中 隐藏遍历整表数据的细节 只需要传入entity的类型 然后直接接收输出的数据列表即可
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
