java中繼承+介面+泛型的無解組合

來源:互聯網
上載者:User

不廢話直接上代碼:

 

工程結構圖:

 

實體User:

package com.smonk.user.entity;public class User {//....}

IBaseDao:

package com.smonk.common.base;import java.io.Serializable;import java.util.List;public interface IBaseDao<T, ID extends Serializable> { public abstract List<T> findAll(); /**  * 尋找所有,並分頁  * @param page 要返回的頁數  * @param pageSize 沒有記錄數  * @return  */ public abstract List<T> findAll(int page, int pageSize); public abstract void save(T entity); public abstract void delete(T entity); /**  * 與findByProperty相似,當properyName == value 時把相應的記錄刪除  */ public abstract void deleteByProperty(String propertyName, Object value); public abstract List<T> findByExample(T example); /**  * 通過屬性尋找  * @param propertyName 屬性名稱  * @param value 屬性的值  * @return  */ public abstract List<T> findByProperty(String propertyName, Object value); /**  * 通過多個屬性尋找  * @param propertyNames 屬性名稱數組  * @param values 屬性值數組  * @return  */ public abstract List<T> findByPropertys(String[] propertyNames,   Object[] values); /**  * 通過多個屬性尋找,並分頁, 屬性名稱數組和屬性值數組的序列要對應  *   * @param propertyNames 屬性名稱數組  * @param values 屬性值數組  * @param page 頁碼  * @param pageSize 每頁內容條數  * @return  */ public List<T> findByPropertys(String[] propertyNames, Object[] values,   int page, int pageSize); /**  * 通過屬性尋找,並分頁, 屬性名稱數組和屬性值數組的序列要對應  * @param propertyNames 屬性名稱  * @param values 屬性值  * @param page 頁碼  * @param pageSize 每頁內容條數  * @return  */ public List<T> findByProperty(String propertyName, Object value, int page,   int pageSize); /**  * 統計所有記錄的總數  * @return 總數  */ public int countAll(); /**  * 統計資料庫中當propertyName=value時的記錄總數  * @param propertyName  * @param value  * @return  */ public int countByProperty(String propertyName, Object value); /**  * 統計資料庫中當多個propertyName=value時的記錄總數  * @param propertyNames  * @param values  * @return  */ public int countByPropertys(String[] propertyNames, Object[] values); public abstract void saveOrUpdate(T entity); public abstract T findById(ID id); public abstract void update(T entity); /**  * 獲得持久化對象的類型  * @return  */ public abstract Class<T> getPersistentClass(); /**  * 尋找並通過某一屬性排序  * @param property 排序依據的順序  * @param isSequence 是否順序排序  */ public List<T> findAndOrderByProperty(int firstResult, int fetchSize,   String propertyName, boolean isSequence); /**  * 尋找並通過某一屬性排序  * @param property 排序依據的順序  * @param isSequence 是否順序排序  */ public List<T> findAllAndOrderByProperty(String propertyName,   boolean isSequence);}

 

BaseHibernateDao:

package com.smonk.common.base;import java.io.Serializable;import java.lang.reflect.ParameterizedType;import java.util.List;import org.hibernate.Query;import org.springframework.orm.hibernate3.support.HibernateDaoSupport;public abstract class BaseHibernateDao<T, ID extends Serializable> extendsHibernateDaoSupport implements IBaseDao<T, ID> {private Class<T> persistentClass;@SuppressWarnings("unchecked")public BaseHibernateDao() {// 擷取持久化對象的類型this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];}public Class<T> getPersistentClass() {return persistentClass;}/** * 通過id尋找 * @param id * @return */@SuppressWarnings("unchecked")public T findById(ID id) {return (T) this.getHibernateTemplate().get(getPersistentClass(), id);}public void save(T entity) {this.getHibernateTemplate().save(entity);}/** * 刪除 */public void delete(T entity) {this.getHibernateTemplate().delete(entity);}/** * 通過屬性刪除 */public void deleteByProperty(String propertyName, Object value) {String queryString = "delete from " + getPersistentClass().getName()+ " as model where model." + propertyName + "= ?";Query query = this.getSession().createQuery(queryString);query.setParameter(0, value);query.executeUpdate();}/** * saveOrUpdate */public void saveOrUpdate(T entity) {this.getHibernateTemplate().saveOrUpdate(entity);}/** * 更新 */public void update(T entity) {this.getHibernateTemplate().update(entity);}/** * 分頁尋找所有的記錄 * @param page 要返回的頁數 * @param pageSize 沒有記錄數 * @return */public List<T> findAll(int page, int pageSize) {String queryString = "from " + getPersistentClass().getName();Query query = this.getSession().createQuery(queryString);int firstResult = (page - 1) * pageSize;query.setFirstResult(firstResult);query.setMaxResults(pageSize);return query.list();}/** * 統計所有記錄的總數 * @return 總數 */public int countAll() {String queryString = "select count(*) from "+ getPersistentClass().getName();Query query = this.getSession().createQuery(queryString);List list = query.list();Long result = (Long) list.get(0);return result.intValue();}/** * find By Example * @param entity * @return */@SuppressWarnings("unchecked")public List<T> findByExample(T entity) {return this.getHibernateTemplate().findByExample(entity);}@SuppressWarnings("unchecked")public List<T> findAll() {return this.getHibernateTemplate().find("from " + getPersistentClass().getName());}/** * 通過屬性尋找 * @param propertyName 屬性名稱 * @param value 屬性的值 * @return */@SuppressWarnings("unchecked")public List<T> findByProperty(String propertyName, Object value) {String queryString = "from " + getPersistentClass().getName()+ " as model where model." + propertyName + "= ?";return this.getHibernateTemplate().find(queryString, value);}/** * 通過多個屬性群組合查詢 * @param propertyNames 屬性名稱數組 * @param values 對應於propertyNames的值 return 匹配的結果 */public List<T> findByPropertys(String[] propertyNames, Object[] values) {StringBuffer strBuffer = new StringBuffer();strBuffer.append("from " + getPersistentClass().getName());strBuffer.append(" as model where ");for (int i = 0; i < propertyNames.length; i++) {if (i != 0)strBuffer.append(" and");strBuffer.append(" model.");strBuffer.append(propertyNames[i]);strBuffer.append("=");strBuffer.append("? ");}String queryString = strBuffer.toString();return this.getHibernateTemplate().find(queryString, values);}/** * 通過屬性尋找並分頁 * @param propertyName 屬性名稱 * @param value 屬性值 * @param page 頁數 * @param pageSize 每頁顯示條數 */public List<T> findByProperty(String propertyName, Object value, int page,int pageSize) {return this.findByPropertys(new String[] { propertyName },new Object[] { value }, page, pageSize);}/** * 通過多個屬性群組合查詢 * @param propertyNames 屬性名稱數組 * @param values 對應於propertyNames的值 * @param page 頁數 * @param pageSize 每頁顯示數 return 匹配的結果 return 匹配的結果 */public List<T> findByPropertys(String[] propertyNames, Object[] values,int page, int pageSize) {StringBuffer strBuffer = new StringBuffer();strBuffer.append("from " + getPersistentClass().getName());strBuffer.append(" as model where ");for (int i = 0; i < propertyNames.length; i++) {if (i != 0)strBuffer.append(" and");strBuffer.append(" model.");strBuffer.append(propertyNames[i]);strBuffer.append("=");strBuffer.append("? ");}String queryString = strBuffer.toString();int firstResult = (page - 1) * pageSize;Query query = this.getSession().createQuery(queryString);query.setFirstResult(firstResult);query.setMaxResults(pageSize);for (int i = 0; i < values.length; i++) {query.setParameter(i, values[i]);}return query.list();}/** * 通過屬性統計數量 * @param propertyName 屬性名稱 * @param value 屬性值 */public int countByProperty(String propertyName, Object value) {String[] propertyNames = new String[] { propertyName };Object[] values = new Object[] { value };return this.countByPropertys(propertyNames, values);}/** * 通過多個屬性統計數量 * @param propertyNames 屬性名稱數組 * @param values 對應的屬性值數組 return */public int countByPropertys(String[] propertyNames, Object[] values) {StringBuffer strBuffer = new StringBuffer();strBuffer.append("select count(*) from "+ getPersistentClass().getName());strBuffer.append(" as model where ");for (int i = 0; i < propertyNames.length; i++) {if (i != 0)strBuffer.append(" and");strBuffer.append(" model.");strBuffer.append(propertyNames[i]);strBuffer.append("=");strBuffer.append("? ");}String queryString = strBuffer.toString();Query query = this.getSession().createQuery(queryString);for (int i = 0; i < values.length; i++) {query.setParameter(i, values[i]);}List list = query.list();Long result = (Long) list.get(0);return result.intValue();}/** * 尋找T並通過某一屬性排序 * @param property 排序依據的順序 * @param isSequence 是否順序排序,false為倒序 */public List<T> findAndOrderByProperty(int firstResult, int fetchSize,String propertyName, boolean isSequence) {String queryString = "from " + getPersistentClass().getName()+ " as model order by model." + propertyName;if (isSequence == false) {queryString = queryString + " DESC";}Query queryObject = getSession().createQuery(queryString);queryObject.setFirstResult(firstResult);queryObject.setMaxResults(fetchSize);return queryObject.list();}/** * 尋找所有並通過某個屬性排序 * @param propertyName 排序依據的屬性名稱 * @param isSequence 是否順序排列 */public List<T> findAllAndOrderByProperty(String propertyName,boolean isSequence) {String queryString = "from " + getPersistentClass().getName()+ " as model order by model." + propertyName;if (isSequence == false) {queryString = queryString + " DESC";}Query queryObject = getSession().createQuery(queryString);return queryObject.list();}}

IUserDao:

package com.smonk.user.dao;import com.smonk.common.base.IBaseDao;import com.smonk.user.entity.User;public interface IUserDao extends IBaseDao<User, Integer> {/** * 通過使用者名稱尋找使用者 * @param userName 使用者名稱 * @return TUser 使用者物件,如果使用者名稱不存在返回null */public User findByUserName(String userName);}

UserHibernateDao:

package com.smonk.user.dao;import java.util.List;import com.smonk.common.base.BaseHibernateDao;import com.smonk.user.entity.User;public class UserHibernateDao extends BaseHibernateDao<User, Integer> implementsIUserDao {// property constantspublic static final String USER_NAME = "userName";/** * 通過名稱尋找使用者 * @return User */public User findByUserName(String userName) {List<User> userList = super.findByProperty(USER_NAME, userName);if (userList.size() != 0) {return userList.get(0);} else {return null;}}public static void main(String[] args) {Integer id = 10;IUserDao dao = new UserHibernateDao();dao.findById(id);}}

請看只有寥寥幾句的UserDao擁有多少功能!!!:

 

親,請問這樣的架構省了多少代碼?省了多少人天?省了多少枯燥與煩擾?。。。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.