我想添加一种我设法使用Native Queries
. 我从@Bohemian 的回答中获得了一些灵感。首先,在服务层,我们将对象列表拆分为块,然后在DAO层,我们插入每个块。
服务
@Override
public void massInsert(List<Object> objects) throws Exception {
// First, let's split the list in chunks.
final int chunkSize = 50;
final AtomicInteger counter = new AtomicInteger();
final Collection<List<Object>> result =
objects.stream().collect(Collectors.groupingBy(it -> counter.getAndIncrement() / chunkSize)).values();
// Now, for each iteration, we will insert the corresponding details.
for (List<Objects> oList : result) {
this.dao.massInsert(oList);
}
}
道
@Override
public void massInsert(List<Object> objects) throws Exception {
Session session = this.sessionFactory.getCurrentSession();
// Create the query. It is important to consider that we will be using a
// native query, which we will build from scratch. This is done in order to improve the insert speed.
String hql = "insert into TABLE (column1, column2) VALUES ";
// For each object, add a new object to insert.
// In the end we will need to remove the last comma.
for (int i = 0; i < objects.size(); i++) {
hql = hql.concat("(?, ?),");
}
hql = hql.substring(0, hql.length()-1);
// Create the query.
Query query = session.createSQLQuery(hql);
// Now, for each object, set the needed parameters.
int index = 1;
for (Object o : objects) {
query.setParameter(index++, o.getAttribute1());
query.setParameter(index++, o.getAttribute2());
}
// Execute the query.
query.executeUpdate();
}
它比逐行插入要快得多。希望能帮助到你。