Hibernate自動生成DAOの修正方法

1970 ワード

Hibernate自動生成DAOの修正方法を転載
MyEclipseでhibernateインバースエンジニアリングで生成されたDAOを使用すると、トランザクションが使用されていないため、オブジェクトがデータベースに格納されない現象が発生します.DAOのコメントは次のとおりです.
/**
 * A data access object (DAO) providing persistence and search support for User
 * entities. Transaction control of the save(), update() and delete() operations
 * can directly support Spring container-managed transactions or they can be
 * augmented to handle user-managed Spring transactions. Each of these methods
 * provides additional information for how to configure it for the desired type
 * of transaction control.
 * 
 * @see org.hibernate.entity.User
 * @author MyEclipse Persistence Tools
 */

解決方法一、Springを用いたトランザクション管理
メソッド2、DAOの変更、トランザクションの追加
もちろん、daoオブジェクトを呼び出すコードの前後にトランザクション制御を加えることができますが、これによりdaoのデータベース操作のカプセル化が破壊され、ビジネス層に永続層コードがドープされます.以下の変更を行います.
import org.hibernate.Session;
import org.hibernate.Transaction;
public void save(Resource transientInstance) {
        log.debug("saving Resource instance");
        try {
        Session session = getSession();
         Transaction tr = session.beginTransaction(); //    
          session.save(transientInstance);
        tr.commit();   //    
         session.flush();    //    
            log.debug("save successful");
        } catch (RuntimeException re) {
            log.error("save failed", re);
            throw re;
        }
    }
public void delete(Resource persistentInstance) {
        log.debug("deleting Resource instance");
        try {
        Session session = getSession();
    Transaction tr = session.beginTransaction();        
            session.delete(persistentInstance);
            tr.commit();
            session.flush();
            log.debug("delete successful");
        } catch (RuntimeException re) {
            log.error("delete failed", re);
            throw re;
        }
    }