Hibernate データの削除(Delete)

2008/07/03 14:05Update
TAGS: Hibernate | データ削除 | delete

Hibernateでは、Session.delete(Object)メソッドを用いて、データの削除を行います。


データの削除例
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
* AppSuperDao: 親DAOクラス(定義の解説略)
* UserMstDao:テーブル USER_MSTを操作するクラス
*/
public class UserMstDao extends AppSuperDao {
    /**
     * セッションを取得する(共通化すべきであるメソッド)
     * @return Session
     */
    private Session getSession() {
        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
        Session s = sessionFactory.openSession();
    
        return s;
    }


    /**
     * UserMstをデータベースから削除する
     * @param userMst 更新対象
     */
    public void delete(UserMst userMst) {
        getSession().delete(userMst); //削除
    }
    
}



Test用クラス
class Test {
    public static void main(String []args) {
        UserMstDao dao = new UserMstDao();
        
        //データ取得
        UserMst userMst = dao.get("001");
        
        
        //トランザクション開始(トランザクションの処理を共通化すべきである)
        Transaction transaction = dao.getSession().beginTransaction();
        
        try {
            //データ削除
            dao.delete(userMst);
            //トランザクション・コミット
            transaction.commit();
        } catch (Exception e) {
            //エラーの場合、トランザクション・ロールバック
            transaction.rollback();
        }
    }
}

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

Sponsored Link


Comments