gpt4 book ai didi

java - hibernate nativesqlquery批量插入

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:25:58 25 4
gpt4 key购买 nike

出于不需要透露的原因,我需要使用 hibernate 层运行一系列 native SQL 语句。它们是“insert abc(column1,column2) values(:column1List, :column2List)”形式的相同语句(相同的绑定(bind)变量)。

如果可能的话,我想将其作为批量插入来执行。可以吗?如果是怎么办?

我试过了
sqlQuery = session.createSQLQuery(sqlQuery);
sqlQuery.setParameterList(.....)

我想我找到了原因,但我不确定发生了什么。 insert 语句有超过 2 列,hibernate 正在将其更改为 insert into abc(column1, column2, column3, column4,column5, column6) values ( ?,?, (?,?),(?,?),(? ,?),?)

最佳答案

您可能想看看使用 JDBC 进行批量插入,这将消除与 hibernate 相关的开销,并允许您处理预定义参数列表

import java.sql.Connection;
import java.sql.PreparedStatement;

//...

String sql = "insert into employee (name, city, phone) values (?, ?, ?)";
org.hibernate.Session sess = (org.hibernate.Session) em.getDelegate();
Connection conn = sess.connection();
PreparedStatement ps = connection.prepareStatement(sql);

for (Employee employee: employees) {

ps.setString(1, employee.getName());
ps.setString(2, employee.getCity());
ps.setString(3, employee.getPhone());
ps.addBatch();
}
ps.executeBatch();
ps.close();
connection.close();

示例取自 ( http://viralpatel.net/blogs/batch-insert-in-java-jdbc/ )

关于java - hibernate nativesqlquery批量插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21387203/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com