How to bulk import data in Hibernate?
Batch importing data using Hibernate can be done by following these steps:
- Create a collection or array containing the data to be imported.
- Obtain the Session object in Hibernate.
- Create a SQL query using the createSQLQuery method of Session.
- Set parameters using the setParameters method in an SQL query.
- Pass a collection or array as a parameter by using the setParameterList method in an SQL query.
- Use the executeUpdate method of the SQL query to perform a batch import operation.
- Commit the transaction and close the session.
Here is an example code:
List<User> userList = // 要导入的用户数据集合
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
String sql = "INSERT INTO user (id, name, age) VALUES (:id, :name, :age)";
SQLQuery query = session.createSQLQuery(sql);
query.setParameterList("id", userList.stream().map(User::getId).collect(Collectors.toList()));
query.setParameterList("name", userList.stream().map(User::getName).collect(Collectors.toList()));
query.setParameterList("age", userList.stream().map(User::getAge).collect(Collectors.toList()));
int rowsAffected = query.executeUpdate();
transaction.commit();
session.close();
Please note that the above example assumes you have an entity class named “User” with properties such as “id”, “name”, and “age”. You will need to make the necessary changes according to your entity class and database table structure.
In addition, you also need to configure Hibernate’s SessionFactory according to your specific environment.