I want to insert records in database using Hibernate Native SQL.The code is like below
Session session = sessionFactory.openSession();
Transaction tx = ses
Here is the same example for Java 8, Hibernate-JPA 2.1:
@Repository
public class SampleNativeQueryRepository {
private final Logger log = LoggerFactory.getLogger(SampleNativeQueryRepository.class);
@PersistenceContext
private EntityManager em;
public void bulkInsertName(List list){
Session hibernateSession = em.unwrap(Session.class);
String sql = "insert into sampletbl (name) values (:name) ";
hibernateSession.doWork(connection -> {
try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
int i = 1;
for(String name : list) {
preparedStatement.setString(1, name);
preparedStatement.addBatch();
//Batch size: 20
if (i % 20 == 0) {
preparedStatement.executeBatch();
}
i++;
}
preparedStatement.executeBatch();
} catch (SQLException e) {
log.error("An exception occurred in SampleNativeQueryRepository.bulkInsertName: {}", e);
}
});
}
}