我最終實現了自己的存儲庫。這個表現非常好,2s而不是35s之前插入50000個元素。這個代碼的問題是它不能防止sql注入。
我也嘗試使用setParameter(1, ...)
來構建查詢,但JPA需要很長時間才能做到這一點。
class ObjectRepositoryImpl implements DemandGroupSalesOfDayCustomRepository {
private static final int INSERT_BATCH_SIZE = 50000;
@Autowired
private EntityManager entityManager;
@Override
public void blindInsert(List<SomeObject> objects) {
partition(objects, INSERT_BATCH_SIZE).forEach(this::insertAll);
}
private void insertAll(List<SomeObject> objects) {
String values = objects.stream().map(this::renderSqlForObj).collect(joining(","));
String insertSQL = "INSERT INTO mytable (date, feature1, feature2, quantity) VALUES ";
entityManager.createNativeQuery(insertSQL + values).executeUpdate();
entityManager.flush();
entityManager.clear();
}
private String renderSqlForObj(Object obj) {
return "('" + obj.getDate() + "','" +
obj.getFeature1() + "','" +
obj.getFeature2() + "'," +
obj.getQuantity() + ")";
}
}
嘗試實現彈簧數據JPA批量插入 – Kushan