Hibernate HQLで insert/update/delete

2008/09/12 21:20Update
TAGS: Hibernate | HQLクエリ | insert | update | delete

Hibernate 3から、バルク(bulk)SQLと呼ばれる書き方で、HQLからデータをinsert(挿入)/update(更新)/delete(削除)することができるようになりました。

例:
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

String hqlUpdate = "update Cat c set c.name = :newName where c.name = :oldName";
int updatedEntities = s.createQuery( hqlUpdate )
        .setString( "newName", newName )
        .setString( "oldName", oldName )
        .executeUpdate();
tx.commit();
session.close();


HQLでupdate処理



■HQL構文:
update Cat c set c.name = :newName where c.name = :oldName

update Cat set name = :newName where name = :oldName


■使用例:
    public static void testHqlUpdate(Session sess) {
        Transaction tr = sess.beginTransaction();
        try {
            Query query = sess.createQuery("update Cat set name=name || :name where id=1")
                .setParameter("name", "_upd");
            
            query.executeUpdate();
            tr.commit();
        } catch (Exception e) {
            tr.rollback();
        }
    }

    
■実行ログ
Hibernate: update Cat set NAME=concat(NAME, ?) where ID=1

■データ
更新前のCatテーブル
ID    NAME    
1    f01


更新後のCatテーブル
ID    NAME    
1    f01_upd    

HQLでdelete処理


■HQL構文:
delete Cat where id=:id

■使用例:
    public static void testHqlDelete(Session sess) {
        Transaction tx = sess.beginTransaction();
        try {
            Query query = sess.createQuery("delete Cat where id=:id")
                .setParameter("id", "4");
            
            query.executeUpdate();
            tx.commit();
        } catch (Exception e) {
            tx.rollback();
        }
    }


■実行ログ
Hibernate: delete from Cat where ID=?

※削除されるテーブルと関連性のあるテーブルのデータが削除されない可能性がありますので、ご注意ください。


HQLでinsert処理



■HQL構文:
insert into エンティティ名 (プロパティ1, プロパティ2, ...) select ... from ... where ...

※Hibernate では、「insert into ... select ...」の形式しかサポートしていません。
※insert into ... values... の形式だと、エラーになります。
※id プロパティに対して、自動生成戦略の場合、明示的に id プロパティを指定するか、プロパティリストから外すかを選択することができます。
insert into Cat(id, name) select ...

insert into Cat(name) select ...
※version や timestampとしてマッピングされるプロパティに対しても、idプロパティと同様に対処されることができます。


■使用例:
    public static void testHqlInsert(Session sess) {
        Transaction tx = sess.beginTransaction();
        try {
            Query query = sess.createQuery("insert into Cat(id, name) select d.id, d.name from CatBak where d.name like :name)")
                .setParameter("name", "%f%");
            
            query.executeUpdate();
            tx.commit();
        } catch (Exception e) {
            tx.rollback();
        }
    }
    

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

Sponsored Link


Comments