(三)利用泛型反射机制实现增加,删除,更新,查询操作(支持继承基类)

/**
 * 基类dao,抽象封装所有的操作
 *
 */
public class BaseDao {
	private DbUtil dbUtil = DbUtil.getInstance();
	//public Connection connection = dbUtil.getConnection();
	private final static int CURD_ADD = 0;
	private final static int CURD_UPDATE = 1;
	private final static int CURD_FIND = 2;
	private final static int CURD_SELECT = 3;
	private final static int CURD_DELETE = 4;
	private final static int CURD_COUNT = 5;
	private Class t; 	 
	
	
	public BaseDao(){
		Type genericSuperclass = this.getClass().getGenericSuperclass();//获得超类
		if(genericSuperclass instanceof ParameterizedType){
			Type[] actualTypeArguments = ((ParameterizedType)genericSuperclass).getActualTypeArguments();
			if(actualTypeArguments != null && actualTypeArguments.length > 0){
				t = (Class) actualTypeArguments[0];
			}
		}
		//System.out.println(t.getSimpleName());
	}
	
	
	/**
	 * 抽象封装数据库添加操作
	 * @param t
	 * @return
	 */
	public boolean add(T t){
		String sql = buildSql(CURD_ADD);
		try {
			PreparedStatement prepareStatement = dbUtil.getConnection().prepareStatement(sql);
			prepareStatement = setPreparedStatement(t,prepareStatement,CURD_ADD);
			int rst = prepareStatement.executeUpdate();
			dbUtil.releaseConnection();
			return rst > 0;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}
	
	/**
	 * 数据库更新操作抽象封装
	 * @param t
	 * @return
	 */
	public boolean update(T t){
		String sql = buildSql( CURD_UPDATE);
		try {
			PreparedStatement prepareStatement = dbUtil.getConnection().prepareStatement(sql);
			prepareStatement = setPreparedStatement(t,prepareStatement,CURD_UPDATE);
			int rst = prepareStatement.executeUpdate();
			dbUtil.releaseConnection();
			return rst > 0;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}
	
	/**
	 * 数据库查询单个实体抽象封装
	 * @param id
	 * @return
	 */
	public T find(int id){
		String sql = buildSql(CURD_FIND);
		T newInstance = null;
		try {
			PreparedStatement prepareStatement = dbUtil.getConnection().prepareStatement(sql);
			prepareStatement.setObject(1, id);
			ResultSet executeQuery = prepareStatement.executeQuery();
			if(executeQuery.next()){
				newInstance = (T) t.newInstance();
				newInstance = setParams(newInstance,executeQuery);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		dbUtil.releaseConnection();
		return newInstance;
	}
	
	
	
	/**
	 * 给从数据库获取的数据赋值并实例化
	 * @param newInstance
	 * @param executeQuery
	 * @return
	 */
	private T setParams(T newInstance, ResultSet executeQuery) {
		// TODO Auto-generated method stub
		//首先获取自身定义的字段
		Field[] declaredFields = newInstance.getClass().getDeclaredFields();
		try {
			for(Field field :declaredFields){
				field.setAccessible(true);
				if(field.isAnnotationPresent(Column.class)){
					Column annotation = field.getAnnotation(Column.class);
					if(!annotation.isForeignEntity()){
						//如果不是自定义对象
						field.set(newInstance, executeQuery.getObject(annotation.name()));
					}else{
						Blob blob = executeQuery.getBlob(annotation.name());
						ObjectInputStream objectInputStream = new ObjectInputStream(blob.getBinaryStream());
						field.set(newInstance, objectInputStream.readObject());
					}
				}else{
					field.set(newInstance, executeQuery.getObject(StringUtil.convertToUnderline(field.getName())));
				}
			}
			Field[] parentFields = newInstance.getClass().getFields();
			for(Field field :parentFields){
				field.setAccessible(true);
				if(field.isAnnotationPresent(Column.class)){
					Column annotation = field.getAnnotation(Column.class);
					field.set(newInstance, executeQuery.getObject(annotation.name()));
				}else{
					field.set(newInstance, executeQuery.getObject(StringUtil.convertToUnderline(field.getName())));
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return newInstance;
	}

	/**
	 * 设置数据库链接信息相关值即复制给变量
	 * @param prepareStatement
	 * @return
	 */
	private PreparedStatement setPreparedStatement(T t,
			PreparedStatement prepareStatement,int curdType) {
		// TODO Auto-generated method stub
		Field[] declaredFields = t.getClass().getDeclaredFields();
		try {
			switch (curdType) {
				case CURD_ADD:{
					int index = 1;
					for(int i = 0;i fields = getTableFields();
		String[] values = new String[fields.size()];
		Arrays.fill(values, "?");
		for(int i=0;i  fields = getTableFields();
		return StringUtil.join(fields, ",");
	}


	/**
	 * 获取数据库表的所有字段
	 * @param t
	 * @return
	 */
	private List getTableFields() {
		// TODO Auto-generated method stub
		List ret = new ArrayList();
		Field[] declaredFields = t.getDeclaredFields();
		for(Field field : declaredFields){
			//如果字段被注解,则以注解的为准
			if(field.isAnnotationPresent(Column.class)){
				ret.add(field.getAnnotation(Column.class).name());
				continue;
			}
			ret.add(StringUtil.convertToUnderline(field.getName()));
		}
		if(BaseEntity.class.isAssignableFrom(t)){
			//说明继承自BaseEntity
			Field[] fields = t.getFields();
			for(Field field : fields){
				//如果字段被注解,则以注解的为准
				if(field.isAnnotationPresent(Column.class)){
					ret.add(field.getAnnotation(Column.class).name());
					continue;
				}
				ret.add(StringUtil.convertToUnderline(field.getName()));
			}
		}
		return ret;
	}

	/**
	 * 获取实体对应的数据库表名
	 * @return
	 */
	private String getTableName() {
		// TODO Auto-generated method stub
		String tableName = StringUtil.convertToUnderline(t.getSimpleName());
		//如果注解了表名,则以注解的名称为准
		if(t.isAnnotationPresent(Table.class)){
			String prefix = t.getAnnotation(Table.class).prefix();
			String sufix = t.getAnnotation(Table.class).sufix();
			tableName = StringUtil.isEmpty(prefix) ? "" : prefix + "_";
			tableName += t.getAnnotation(Table.class).tableName();
			tableName += StringUtil.isEmpty(sufix) ? "" : "_" + sufix;
		}
		return tableName;
	}


	/**
	 * 关闭数据库链接
	 */
	public void closeConnection(){
		dbUtil.releaseConnection();
	}
}

思路简要分析:用默认构造方法获得具体类型,buildesql拼接sql语句,SetparperedStastement获得各个操作预处理集,然后处理结果集。

你可能感兴趣的:(封装一个自己的数据库框架)