Source List Insert Query in Jpa / hibernate + Spring

I want to insert a list of objects in my db. In the particular case, I know that their primary key (not the auto-generator) does not exist yet. Since I need to insert a large collection, it save(Iterable<Obj> objects)should slow down.

Therefore, I am considering using my own query. inline request in hibernate + spring

In the previous answer, he does not say how to insert a collection of objects. Is it possible?

@Query("insert into my_table (date, feature1, feature2, quantity) VALUES <I do not know what to add here>", nativeQuery = true)
void insert(List<Obj> objs);

Of course, if you have a better solution overall, it is even better.

+4
source share
1 answer

. , 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() + ")";
    }
}
+1

Source: https://habr.com/ru/post/1658919/


All Articles