- Hibernate 教程
- Hibernate - 首页
- ORM - 概述
- Hibernate - 概述
- Hibernate - 架构
- Hibernate - 环境
- Hibernate - 配置
- Hibernate - 会话
- Hibernate - 持久化类
- Hibernate - 映射文件
- Hibernate - 映射类型
- Hibernate - 示例
- Hibernate - O/R 映射
- Hibernate - 级联类型
- Hibernate - 注解
- Hibernate - 查询语言
- Hibernate - Criteria 查询
- Hibernate - 原生 SQL
- Hibernate - 缓存
- Hibernate - 实体生命周期
- Hibernate - 批量处理
- Hibernate - 拦截器
- Hibernate - ID 生成器
- Hibernate - 保存图片
- Hibernate - log4j 集成
- Hibernate - Spring 集成
- Hibernate - Struts 2 集成
- Hibernate - Web 应用
- 映射表示例
- Hibernate - 表继承策略(每个层次结构一张表)
- Hibernate - 表继承策略(每个具体类一张表)
- Hibernate - 表继承策略(每个子类一张表)
- Hibernate 有用资源
- Hibernate - 问题与解答
- Hibernate - 快速指南
- Hibernate - 有用资源
- 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 会将所有持久化对象缓存在会话级缓存中,最终您的应用程序会在大约第 50,000 行出现 OutOfMemoryException 错误。如果您使用 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://127.0.0.1/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 条记录。