Need to insert 100000 rows in mysql using hibernate in under 5 seconds

前端 未结 4 472
我寻月下人不归
我寻月下人不归 2021-01-30 23:38

I am trying to insert 100,000 rows in a MYSQL table under 5 seconds using Hibernate(JPA). I have tried every trick hibernate offers and still can not do better than 35 seconds.

4条回答
  •  无人及你
    2021-01-31 00:10

    After trying all possible solutions I finally found a solution to insert 100,000 rows under 5 seconds!

    Things I tried:

    1) Replaced hibernate/database's AUTOINCREMENT/GENERATED id's by self generated ID's using AtomicInteger

    2) Enabling batch_inserts with batch_size=50

    3) Flushing cache after every 'batch_size' number of persist() calls

    4) multithreading (did not attempt this one)

    Finally what worked was using a native multi-insert query and inserting 1000 rows in one sql insert query instead of using persist() on every entity. For inserting 100,000 entities, I create a native query like this "INSERT into MyTable VALUES (x,x,x),(x,x,x).......(x,x,x)" [1000 row inserts in one sql insert query]

    Now it takes around 3 seconds for inserting 100,000 records! So the bottleneck was the orm itself! For bulk inserts, the only thing that seems to work is native insert queries!

提交回复
热议问题