Hibernate 批处理
hibernate 批处理
某些场景下,我们需要使用 hibernate 将大量的数据上传数据库中。
以下是使用 hibernate 来达到这个的代码片段:
session session = sessionfactory.opensession();
transaction tx = session.begintransaction();
for ( int i=0; i<100000; i++ ) {
employee employee = new employee(.....);
session.save(employee);
}
tx.commit();
session.close();
因为默认下,hibernate 将缓存所有的在会话层缓存中的持久的对象并且最终你的应用程序将和 outofmemoryexception 在第 50000 行的某处相遇。你可以解决这个问题,如果你在 hibernate 使用批处理。
为了使用批处理这个特性,首先设置 hibernate.jdbc.batch_size 作为批处理的尺寸,取一个依赖于对象尺寸的值 20 或 50。这将告诉 hibernate 容器每 x 行为一批插入。为了在你的代码中实现这个我们将需要像以下这样做一些修改:
session session = sessionfactory.opensession();
transaction tx = session.begintransaction();
for ( int i=0; i<100000; i++ ) {
employee employee = new employee(.....);
session.save(employee);
if( i % 50 == 0 ) { // same as the jdbc batch size
//flush a batch of inserts and release memory:
session.flush();
session.clear();
}
}
tx.commit();
session.close();
上面的代码将使 insert 操作良好运行,但是如果你愿意进行 update 操作那么你可以使用以下代码达到这一点:
session session = sessionfactory.opensession();
transaction tx = session.begintransaction();
scrollableresults employeecursor = session.createquery("from employee")
.scroll();
int count = 0;
while ( employeecursor.next() ) {
employee employee = (employee) employeecursor.get(0);
employee.updateemployee();
seession.update(employee);
if ( ++count % 50 == 0 ) {
session.flush();
session.clear();
}
}
tx.commit();
session.close();
批处理样例
让我们通过添加 hibernate.jdbc.batch_size 属性来修改配置文件:
<?xml version="1.0" encoding="utf-8"?>
<!doctype hibernate-configuration system
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.mysqldialect
</property>
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.driver
</property>
<!-- assume students is the database name -->
<property name="hibernate.connection.url">
jdbc:mysql://localhost/test
</property>
<property name="hibernate.connection.username">
root
</property>
<property name="hibernate.connection.password">
root123
</property>
<property name="hibernate.jdbc.batch_size">
50
</property>
<!-- list of xml mapping files -->
<mapping resource="employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
考虑以下 pojo employee 类:
public class employee {
private int id;
private string firstname;
private string lastname;
private int salary;
public employee() {}
public employee(string fname, string lname, int salary) {
this.firstname = fname;
this.lastname = lname;
this.salary = salary;
}
public int getid() {
return id;
}
public void setid( int id ) {
this.id = id;
}
public string getfirstname() {
return firstname;
}
public void setfirstname( string first_name ) {
this.firstname = first_name;
}
public string getlastname() {
return lastname;
}
public void setlastname( string last_name ) {
this.lastname = last_name;
}
public int getsalary() {
return salary;
}
public void setsalary( int salary ) {
this.salary = salary;
}
}
让我们创建以下的 employee 表单来存储 employee 对象:
create table employee ( id int not null auto_increment, first_name varchar(20) default null, last_name varchar(20) default null, salary int default null, primary key (id) );
以下是将 employee 对象和 employee 表单配对的映射文件。
<?xml version="1.0" encoding="utf-8"?>
<!doctype hibernate-mapping public
"-//hibernate/hibernate mapping dtd//en"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="employee" table="employee">
<meta attribute="class-description">
this class contains the employee detail.
</meta>
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
<property name="firstname" column="first_name" type="string"/>
<property name="lastname" column="last_name" type="string"/>
<property name="salary" column="salary" type="int"/>
</class>
</hibernate-mapping>
最后,我们将用 main() 方法来创建我们的应用程序类以运行应用程序,我们将使用 session 对象和可用的 flush() 和 clear() 方法以让 hibernate 持续将这些记录写入数据库而不是在内存中缓存它们。
import java.util.*;
import org.hibernate.hibernateexception;
import org.hibernate.session;
import org.hibernate.transaction;
import org.hibernate.sessionfactory;
import org.hibernate.cfg.configuration;
public class manageemployee {
private static sessionfactory factory;
public static void main(string[] args) {
try{
factory = new configuration().configure().buildsessionfactory();
}catch (throwable ex) {
system.err.println("failed to create sessionfactory object." + ex);
throw new exceptionininitializererror(ex);
}
manageemployee me = new manageemployee();
/* add employee records in batches */
me.addemployees( );
}
/* method to create employee records in batches */
public void addemployees( ){
session session = factory.opensession();
transaction tx = null;
integer employeeid = null;
try{
tx = session.begintransaction();
for ( int i=0; i<100000; i++ ) {
string fname = "first name " + i;
string lname = "last name " + i;
integer salary = i;
employee employee = new employee(fname, lname, salary);
session.save(employee);
if( i % 50 == 0 ) {
session.flush();
session.clear();
}
}
tx.commit();
}catch (hibernateexception e) {
if (tx!=null) tx.rollback();
e.printstacktrace();
}finally {
session.close();
}
return ;
}
}
编译和执行
这里是编译和运行以上提及的应用程序的步骤。确保你已经在处理编译和运行前已经正确设置了 path 和 classpath。
- 如上面解释的那样创建
hibernate.cfg.xml配置文件。 - 如上面显示的那样创建
employee.hbm.xml映射文件。 - 如上面显示的那样创建
employee.java源文件并编译。 - 如上面显示的那样创建
manageemployee.java源文件并编译。 - 执行 manageemployee 二进制代码来运行可以在 employee 表单中创建 100000 个记录的程序。


