spring hibernate註解實現泛型dao

來源:互聯網
上載者:User

寫給像我一樣的菜菜的,高手們麼就不用看了

ssh開發中重複寫dao是個頭疼的事情,可以把dao抽象寫成一個泛型到,網上有好多方法實習,這裡用的是註解(annotation),其實跟xml也差不多。

public class GenericDAOImpl<T, PK extends Serializable> extends
        HibernateDaoSupport implements GenericDAO<T, PK> {

    private Class<T> entityClass;

//可以寫成有參建構函式,但是有些麻煩,直接用反射搞到,可能在實現的時候會報錯,說類型轉換出錯,那麼檢查下是不是把public寫成了private了,以至於整合他的子類無法執行個體化父類的構造方法
    @SuppressWarnings("unchecked")
    public GenericDAOImpl(){
        this.entityClass = (Class<T>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }
//傳統的方法是在xml中加入一個屬性,注入sessionFactory,但是我們可以用註解注入,這個從javaeye上學來的。
    @Resource
    public void setSessionFactory0(SessionFactory sessionFactory) {
        super.setSessionFactory(sessionFactory);
    }

    public Class<T> getEntityClass() {
        return this.entityClass;
    }

。。。。下面的不繼續寫了。

}

 

子類,繼承於泛型dao

@Repository("userDao")
public class UserDaoImpl extends GenericDAOImpl<User, Integer>{

}

是不是方便了許多了,就是一個空類,不用再重複寫get set之類的,如果上面你是用的有參的話xml中要注入實體bean

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.