前言:采用JPA的saveAll进行批量新增时,速度会很慢,可以采用EntityManager进行批量操作。
1. 批量新增
使用EntityManager的persist(Object entity)方法:
@Component
public class ChannelBizImpl implements IChannelBiz {
@PersistenceContext
protected EntityManager em;
@Override
public boolean batchSave(List<ChannelTable> requestList) {
for (ChannelTable table : requestList){
/** 将要批量插入的实例转换为managed(托管)状态 */
em.persist(table);
}
/** 提交事务,实例将会被插入到数据库中 */
em.flush();
em.clear();
return true;
}
}
@Component
public class ChannelBizImpl implements IChannelBiz {
@PersistenceContext
protected EntityManager em;
@Override
public boolean batchSave(List<ChannelTable> requestList) {
for (ChannelTable table : requestList){
/** 将要批量插入的实例转换为managed(托管)状态 */
em.remove(em.merge(table));
}
/** 提交事务,实例将会被插入到数据库中 */
em.flush();
em.clear();
return true;
}
}
2. 批量更新
使用EntityManager的merge(T entity)方法:
@Component
public class ChannelBizImpl implements IChannelBiz {
@PersistenceContext
protected EntityManager em;
@Override
public boolean batchSave(List<ChannelTable> requestList) {
for (ChannelTable table : requestList){
/** 将要批量更新的实例转换为managed(托管)状态 */
em.merge(table);
}
/** 提交事务,实例将会被插入到数据库中 */
em.flush();
em.clear();
return true;
}
}
3. 批量删除
我采用的是SQL的IN函数,在这里有两种方式实现。
1)方式一:
public interface IChannelDao extends JpaRepository<ChannelTable,String> {
@Modifying
@Query("delete from ChannelTable t where t.channelId in :channelIds")
void batchDelete(@Param("channelIds") List<String> channelIds);
}
方式二:
@Component
public class ChannelBizImpl implements IChannelBiz {
@PersistenceContext
protected EntityManager em;
@Override
public boolean batchSave(List<ChannelTable> requestList) {
for (ChannelTable table : requestList){
/**
* em.remove(table)或者em.merge(table);em.remove(table):
* java.lang.IllegalArgumentException: Removing a detached instance
* 移除已经持久化的对象
*/
em.remove(em.merge(table));
}
/** 提交事务,实例将会被插入到数据库中 */
em.flush();
em.clear();
return true;
}
}