2016-06-16 12 views
3

私は、私のDAOクラスにmakePersistentというメソッドを持っています。 私たちはすべてのDAOクラスでこのメソッドを持っていますが、私はこのメソッドを共通フォーマットに変換する必要があります。だからそれを行う方法はありますか? HolidayDaoクラスでUserDaoクラスで一般的な引数渡しメソッド

方法

public void makePersistent(User model) throws InfrastructureException { 
     try { 
      getSession().saveOrUpdate(model); 
      getSession().flush(); 
      getSession().clear(); 
     } catch (org.hibernate.StaleObjectStateException ex) { 
      throw new InfrastructureException(Labels.getString("com.tran.msg.objectDeletedOrUpdated")); 
     } catch (HibernateException ex) { 
      throw new InfrastructureException(ex); 
     } 
    } 

方法

public void makePersistent(Holiday model) throws InfrastructureException { 
     try { 
      getSession().saveOrUpdate(model); 
      getSession().flush(); 
      getSession().clear(); 
     } catch (org.hibernate.StaleObjectStateException ex) { 
      throw new InfrastructureException(Labels.getString("com.tran.msg.objectDeletedOrUpdated")); 
     } catch (HibernateException ex) { 
      throw new InfrastructureException(ex); 
     } 
    } 

この冗長なコーディングを取り除くために私を助けてください。 ありがとうございます。

答えて

2
Just use Object the hibernate will persist it. 


public void makePersistent(Object model) throws InfrastructureException { 
     try { 
      getSession().saveOrUpdate(model); 
      getSession().flush(); 
      getSession().clear(); 
     } catch (org.hibernate.StaleObjectStateException ex) { 
      throw new InfrastructureException(Labels.getString("com.tran.msg.objectDeletedOrUpdaed")); 
     } catch (HibernateException ex) { 
      throw new InfrastructureException(ex); 
     } 
    } 
+0

パーフェクトthats私が探しているもの。ありがとうございました。 – ambarox

1

タイプパラメータを使用してDAOのスーパークラスを作成し、適切なタイプ引数を使用してそのスーパークラスを拡張するようにします。たとえば:あなたはすべてのDAOクラスで再びそれを実装する必要はありませんので

public class BaseDao<T> { 

    public void makePersistent(T model) throws InfrastructureException { 
     try { 
      getSession().saveOrUpdate(model); 
      getSession().flush(); 
      getSession().clear(); 
     } catch (org.hibernate.StaleObjectStateException ex) { 
      throw new InfrastructureException(Labels.getString("com.tran.msg.objectDeletedOrUpdated")); 
     } catch (HibernateException ex) { 
      throw new InfrastructureException(ex); 
     } 
    } 
} 

public class UserDao extends BaseDao<User> { 
    // ... 
} 

public class HolidayDao extends BaseDao<Holiday> { 
    // ... 
} 

UserDaoHolidayDaoは、BaseDaoからmakePersistentメソッドを継承します。

関連する問題