java中继承+接口+泛型的无解组合

本文介绍了一种基于Java的通用DAO设计模式,通过抽象基类BaseHibernateDao实现了CRUD等常见操作,极大减少了开发工作量。具体展示了User实体类、IBaseDao接口及其实现类BaseHibernateDao的代码细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

不废话直接上代码:

 

工程结构图:

 

实体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> extends
		HibernateDaoSupport 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> implements
		IUserDao {

	// property constants
	public 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拥有多少功能!!!:

 

亲,请问这样的架构省了多少代码?省了多少人天?省了多少枯燥与烦扰?。。。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值