Hibernate データの削除(Delete)
2008/07/03 14:05Update
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();
}
}
}
Sponsored Link
- Relative Articles
- Hibernate設定ファイルその1 - hibernate.cfg.xml - (2008/07/09 14:08)
- Hibernate c3p0 - よく利用されているコネクションプーリング - (2008/07/09 15:00)
- Hibernate 方言(Dialect)一覧 - (2008/07/09 15:10)
- Hibernate のSessionとSessionFactory - (2008/07/09 15:51)
- ThreadLocal でHibernate Session を効率的に管理する - (2008/07/09 18:43)
- Hibernateで複数のDBに接続するには? - (2008/07/09 18:47)
- Hibernateとは - (2008/07/11 14:23)
- Hibernate のインストール - (2008/07/24 11:01)
- Hibernate の開発手順 - (2008/07/24 12:44)
- Hibernate SQLをログに出力方法 - (2008/07/30 16:06)