Hibernate-batch-processing

提供:Dev Guides
移動先:案内検索

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の数値にバッチサイズとして設定します。 これは、すべての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テーブルにマッピングするためのマッピングファイルです-

<?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レコードが作成されます。