📅  最后修改于: 2020-11-16 07:04:03             🧑  作者: Mango
考虑一种情况,当您需要使用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将所有持久化的对象缓存在会话级缓存中,最终您的应用程序将在第50,000行附近出现OutOfMemoryException崩溃。如果您将批处理与Hibernate一起使用,则可以解决此问题。
要使用批处理功能,首先将hibernate.jdbc.batch_size设置为批处理大小,根据对象大小将其设置为20或50。这将告诉休眠容器每隔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属性-
org.hibernate.dialect.MySQLDialect
com.mysql.jdbc.Driver
jdbc:mysql://localhost/test
root
root123
50
考虑以下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对象的映射文件-
This class contains the employee detail.
最后,我们将使用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条记录。