Hibernate JDBCでバッチ処理

2008/11/11 11:31Update
TAGS: Hibernate | JDBC | バッチ | 削除 | 更新 | Statement | Connection | PreparedStatement

Hibernateでは、データの更新や挿入、削除などを行うとき、Session.save(...)やSession.delete(...)、Session.update(...)などのメソッドがありますが、大量のデータ(バッチ処理)の場合、OutOfMemoryExceptionを起こったり、効率を低下しまったりすることがあります。

こうした処理の場合、session.flush()やsession.clear()を使って、ある程度のパフォーマンスの改善ができますが、JDBCに比べ性能的には大幅に劣ることも確かめられています。

本文はHibernateでJDBCの使い方について学びます。

手順


1)org.hibernate.Sessionからjava.sql.Connectionを取得
Session session = ...;
Connection connection = sess.connection();


2)ConnectionからPreparedStatement オブジェクトやStatement オブジェクトを生成
PreparedStatement preparedStatement = connection.prepareStatement(sql);


または
Statement statement = connection.createStatement();


3)SQLの実行
statement.executeUpdate(sql);


サンプル


    //sql例: DELETE FROM some_table
    //INSERT... SELECT ...
    public static void testJdbcConnection(Session sess, String sql) {
        //java.sql.Connection
        Connection connection = sess.connection();
        
        Transaction tr = sess.beginTransaction();
        try {
            //パラメータ付き SQL 文
            //PreparedStatement preparedStatement = connection.prepareStatement(sql);
            //preparedStatement.setString(0, "value");
            //preparedStatement.executeUpdate();
            
            Statement statement = connection.createStatement();
            statement.executeUpdate(sql);
            
            tr.commit();
        } catch (SQLException e) {
            tr.rollback();
        }
    }
    


参考資料


Connection (Java 2 プラットフォーム SE v1.4.0)
Hibernate HQLで insert/update/delete

有关作者
Syboos.jp編集長AJavaやオープンソース情報の執筆、Webサイトの開発や運営全般の業務に携わる。

Sponsored Link


Comments

用户名 (required)

Email (will not be published) (required)

URL

Evaluation