SpringMvc+Jdbc泛型反射BaseDao

最近好忙啊,周末还要加班。。。


把这两天研究的代码仍上来,以后有的用。。。数据源是DB2,自己换把。


等有空在BaseService相关也写出来。


spring-mvc.xml


 
	
	Spring公共配置文件 
	
	  
	
	
	
	
	
	
	
	
	
	
	
	 
	  
	

	
	
		
		
		
		
		
		
		
		
		
		
		
		
	
	
	
		
	

	
	
	
	
		
		
	
	
	
		
			
		
	
    
	
	  
		
		  
		
		  
		
		  
	 

web.xml



  Tools
  
    encodingFilter
    org.springframework.web.filter.CharacterEncodingFilter
    true
    
      encoding
      UTF-8
    
  
  
    encodingFilter
    /*
  
  
    org.springframework.web.context.ContextLoaderListener
  
  
    org.springframework.web.util.IntrospectorCleanupListener
  
  
    contextConfigLocation
    classpath:spring/spring-mvc.xml
  
  
    Tools
    org.springframework.web.servlet.DispatcherServlet
    3
    true
  
  
    Tools
    /
  
  
    /index.jsp
  
  
    60
  

Tools-servlet.xml (Tools和项目名称一致)


 
     
     
    
    	 
        
    
     

我的数据库表名间隔是_表示的,的需要处理。

StringTools,java

package com.soft.util;

import org.apache.commons.lang.StringUtils;

public class StringTools {

	/**
	 * 获取表名称
	 * @param entityName
	 * @return
	 */
	public static String getTableName(String entityName) {

		if (StringUtils.isEmpty(entityName)) {

			return null;
		}
		StringBuilder tableName = new StringBuilder();

		int i = 0;
		StringBuilder str = new StringBuilder();
		char[] subStr = entityName.toCharArray();

		while (i < entityName.length()) {
			while (i < entityName.length() && subStr[i] > 'Z') {
				if (Character.isLowerCase(subStr[i])) {
					str.append(String.valueOf(subStr[i]).toUpperCase());
				} else {
					str.append(subStr[i]);
				}
				i++;
			}
			if (str.toString().length() > 0) {
				tableName.append(str.toString() + "_");
			}
			if (i < entityName.length()) {
				str = new StringBuilder();
				str.append(subStr[i++]);
			}
		}
		tableName.append(str.toString());

		return tableName.toString();
	}
	
	/**
	 * 字符串为空
	 * @param str
	 * @return
	 */
	public static boolean isEmpty(String str) {
		return ((str == null) || (str.trim().length() == 0));
	}

	/**
	 * 字符串非空
	 * @param str
	 * @return
	 */
	public static boolean isNotEmpty(String str) {
		return (!(isEmpty(str)));
	}
}

下面是BaseDao.java

package com.soft.dao;

import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.soft.util.QueryResult;

public interface BaseDao extends Serializable{
	/**
     * 插入指定的持久化对象
     * @param obj
     * @return
     */
    void save(T obj);
    /**
     * 修改指定的持久化对象
     * @param obj
     */
    void update(T obj);
    /**
     * 删除指定的持久化对象
     * @param id
     */
    void delete(T obj);
    /**
     * 删除指定id的持久化对象
     * @param id
     */
	void delete(Serializable id);
    /**
     * 全部删除持久化对象
     */
	void deleteAll();
    /**
     * 根据ID检索持久化对象
     */
	T findById(Serializable id);
    /**
     * 检索所有持久化对象
     */
	List findAll();
    /**
     * 检索指定页和指定条数的持久化对象
     * @param pageNo
     * @param pageSize
     */
	QueryResult findByPageList(int pageNo, int pageSize);
    /**
     * 根据条件检索指定页和指定条数的持久化对象
     * @param pageNo
     * @param pageSize
     */
	QueryResult findByPageList(int pageNo, int pageSize,
			Map where);
    /**
     * 根据排序检索指定页和指定条数的持久化对象
     * @param pageNo
     * @param pageSize
     */
	QueryResult findByPageList(int pageNo, int pageSize,
			LinkedHashMap orderby);
    /**
     * 根据条件和排序检索指定页和指定条数的持久化对象
     * @param pageNo
     * @param pageSize
     */
	QueryResult findByPageList(int pageNo, int pageSize,
			Map where, LinkedHashMap orderby);
}

实现BaseDaoImpl.java

package com.soft.dao.impl;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.sql.Types;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import com.soft.dao.BaseDao;
import com.soft.util.QueryResult;
import com.soft.util.StringTools;

/**
 * 实体类名和数据库表名去除(_)后一致,大小写无区别
 */
public class BaseDaoImpl implements BaseDao ,Serializable{

	/**
	 * 序列化版本ID
	 */
	private static final long serialVersionUID = -4404021901527702693L;
	/**
	 * 设置一些操作的常量
	 */
	public static final String SQL_INSERT = "insert";
	public static final String SQL_UPDATE = "update";
	public static final String SQL_DELETE = "delete";

	/**
	 * 泛型
	 */
	private Class entityClass;
	private String simpleName;
	
	/**
	 * 简化数据操作
	 */
	@Resource(name = "jdbcTemplate")
    private JdbcTemplate jdbcTemplate;

	@SuppressWarnings("unchecked")
	public BaseDaoImpl() {
		ParameterizedType type = (ParameterizedType) getClass()
				.getGenericSuperclass();
		entityClass = (Class) type.getActualTypeArguments()[0];
		simpleName = StringTools.getTableName(entityClass.getSimpleName());
		System.out.println("Dao实现类是:" + entityClass.getName());
	}

	@Override
	public void save(T entity) {
		String sql = this.makeSql(SQL_INSERT);
		Object[] args = this.setArgs(entity, SQL_INSERT);
		int[] argTypes = this.setArgTypes(entity, SQL_INSERT);
		jdbcTemplate.update(sql.toString(), args, argTypes);
	}

	@Override
	public void update(T entity) {
		String sql = this.makeSql(SQL_UPDATE);
		Object[] args = this.setArgs(entity, SQL_UPDATE);
		int[] argTypes = this.setArgTypes(entity, SQL_UPDATE);
		jdbcTemplate.update(sql, args, argTypes);
	}

	@Override
	public void delete(T entity) {
		String sql = this.makeSql(SQL_DELETE);
		Object[] args = this.setArgs(entity, SQL_DELETE);
		int[] argTypes = this.setArgTypes(entity, SQL_DELETE);
		jdbcTemplate.update(sql, args, argTypes);
	}

	@Override
	public void delete(Serializable id) {
		String sql = " DELETE FROM " + simpleName
				+ " WHERE id=?";
		jdbcTemplate.update(sql, id);
	}

	@Override
	public void deleteAll() {
		String sql = " TRUNCATE TABLE " + simpleName;
		jdbcTemplate.execute(sql);
	}


	@Override
	public T findById(Serializable id) {
		String sql = "SELECT * FROM " + simpleName
				+ " WHERE id=?";
		RowMapper rowMapper = BeanPropertyRowMapper.newInstance(entityClass);
		return jdbcTemplate.query(sql, rowMapper, id).get(0);
	}

    @Override  
    public List findAll() {  
        String sql = "SELECT * FROM " + simpleName;  
        RowMapper rowMapper = BeanPropertyRowMapper.newInstance(entityClass);  
        return jdbcTemplate.query(sql, rowMapper);  
    }  
  
    @Override  
    public QueryResult findByPageList(int pageNo, int pageSize) {  
        List list = this.find(pageNo, pageSize, null, null);  
        int totalRow = this.count(null);  
        return new QueryResult(list, totalRow);  
    }  
  
    @Override  
    public QueryResult findByPageList(int pageNo, int pageSize, Map where) {  
        List list = this.find(pageNo, pageSize, where, null);  
        int totalRow = this.count(where);  
        return new QueryResult(list, totalRow);  
    }  
  
    @Override  
    public QueryResult findByPageList(int pageNo, int pageSize, LinkedHashMap orderby) {  
        List list = this.find(pageNo, pageSize, null, orderby);  
        int totalRow = this.count(null);  
        return new QueryResult(list, totalRow);  
    }  
  
    @Override  
    public QueryResult findByPageList(int pageNo, int pageSize, Map where,  
            LinkedHashMap orderby) {  
        List list = this.find(pageNo, pageSize, where, orderby);  
        int totalRow = this.count(where);  
        return new QueryResult(list, totalRow);  
    } 

	/**
	 *  组装SQL
	 */
	private String makeSql(String sqlFlag) {
		StringBuffer sql = new StringBuffer();
		Field[] fields = entityClass.getDeclaredFields();
		if (sqlFlag.equals(SQL_INSERT)) {
			sql.append(" INSERT INTO " + simpleName);
			sql.append("(");
			for (int i = 0; fields != null && i < fields.length; i++) {
				fields[i].setAccessible(true); // 暴力反射
				String column = fields[i].getName();
				sql.append(column).append(",");
			}
			sql = sql.deleteCharAt(sql.length() - 1);
			sql.append(") VALUES (");
			for (int i = 0; fields != null && i < fields.length; i++) {
				sql.append("?,");
			}
			sql = sql.deleteCharAt(sql.length() - 1);
			sql.append(")");
		} else if (sqlFlag.equals(SQL_UPDATE)) {
			sql.append(" UPDATE " + simpleName + " SET ");
			for (int i = 0; fields != null && i < fields.length; i++) {
				fields[i].setAccessible(true); // 暴力反射
				String column = fields[i].getName();
				if (column.equals("id")) { // id 代表主键
					continue;
				}
				sql.append(column).append("=").append("?,");
			}
			sql = sql.deleteCharAt(sql.length() - 1);
			sql.append(" WHERE id=?");
		} else if (sqlFlag.equals(SQL_DELETE)) {
			sql.append(" DELETE FROM " + simpleName
					+ " WHERE id=?");
		}
		System.out.println("SQL=" + sql);
		return sql.toString();

	}

	/**
	 *  设置参数
	 */
	private Object[] setArgs(T entity, String sqlFlag) {
		Field[] fields = entityClass.getDeclaredFields();
		if (sqlFlag.equals(SQL_INSERT)) {
			Object[] args = new Object[fields.length];
			for (int i = 0; args != null && i < args.length; i++) {
				try {
					fields[i].setAccessible(true); // 暴力反射
					args[i] = fields[i].get(entity);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			return args;
		} else if (sqlFlag.equals(SQL_UPDATE)) {
			Object[] tempArr = new Object[fields.length];
			for (int i = 0; tempArr != null && i < tempArr.length; i++) {
				try {
					fields[i].setAccessible(true); // 暴力反射
					tempArr[i] = fields[i].get(entity);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			Object[] args = new Object[fields.length];
			System.arraycopy(tempArr, 1, args, 0, tempArr.length - 1); // 数组拷贝
			args[args.length - 1] = tempArr[0];
			return args;
		} else if (sqlFlag.equals(SQL_DELETE)) {
			Object[] args = new Object[1]; // 长度是1
			fields[0].setAccessible(true); // 暴力反射
			try {
				args[0] = fields[0].get(entity);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return args;
		}
		return null;

	}

	/**
	 *  设置参数类型(缺少的用到了再添加)
	 */
	private int[] setArgTypes(T entity, String sqlFlag) {
		Field[] fields = entityClass.getDeclaredFields();
		if (sqlFlag.equals(SQL_INSERT)) {
			int[] argTypes = new int[fields.length];
			try {
				for (int i = 0; argTypes != null && i < argTypes.length; i++) {
					fields[i].setAccessible(true); // 暴力反射
					if (fields[i].get(entity).getClass().getName()
							.equals("java.lang.String")) {
						argTypes[i] = Types.VARCHAR;
					} else if (fields[i].get(entity).getClass().getName()
							.equals("java.lang.Double")) {
						argTypes[i] = Types.DECIMAL;
					} else if (fields[i].get(entity).getClass().getName()
							.equals("java.lang.Integer")) {
						argTypes[i] = Types.INTEGER;
					} else if (fields[i].get(entity).getClass().getName()
							.equals("java.util.Date")) {
						argTypes[i] = Types.DATE;
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return argTypes;
		} else if (sqlFlag.equals(SQL_UPDATE)) {
			int[] tempArgTypes = new int[fields.length];
			int[] argTypes = new int[fields.length];
			try {
				for (int i = 0; tempArgTypes != null && i < tempArgTypes.length; i++) {
					fields[i].setAccessible(true); // 暴力反射
					if (fields[i].get(entity).getClass().getName()
							.equals("java.lang.String")) {
						tempArgTypes[i] = Types.VARCHAR;
					} else if (fields[i].get(entity).getClass().getName()
							.equals("java.lang.Double")) {
						tempArgTypes[i] = Types.DECIMAL;
					} else if (fields[i].get(entity).getClass().getName()
							.equals("java.lang.Integer")) {
						tempArgTypes[i] = Types.INTEGER;
					} else if (fields[i].get(entity).getClass().getName()
							.equals("java.util.Date")) {
						tempArgTypes[i] = Types.DATE;
					}
				}
				System.arraycopy(tempArgTypes, 1, argTypes, 0,
						tempArgTypes.length - 1); // 数组拷贝
				argTypes[argTypes.length - 1] = tempArgTypes[0];

			} catch (Exception e) {
				e.printStackTrace();
			}
			return argTypes;

		} else if (sqlFlag.equals(SQL_DELETE)) {
			int[] argTypes = new int[1]; // 长度是1
			try {
				fields[0].setAccessible(true); // 暴力反射
				if (fields[0].get(entity).getClass().getName()
						.equals("java.lang.String")) {
					argTypes[0] = Types.VARCHAR;
				} else if (fields[0].get(entity).getClass().getName()
						.equals("java.lang.Integer")) {
					argTypes[0] = Types.INTEGER;
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
			return argTypes;
		}
		return null;
	}

	private List find(int pageNo, int pageSize, Map where,
			LinkedHashMap orderby) {
		
		StringBuffer sql = new StringBuffer(
				" SELECT * FROM (SELECT t.*,ROWNUM rn FROM (SELECT * FROM "
						+ simpleName);
		if (where != null && where.size() > 0) {
			sql.append(" WHERE "); // 注意不是where
			for (Map.Entry me : where.entrySet()) {
				String columnName = me.getKey();
				String columnValue = me.getValue();
				sql.append(columnName).append(" ").append(columnValue)
						.append(" AND "); // 没有考虑or的情况
			}
			int endIndex = sql.lastIndexOf("AND");
			if (endIndex > 0) {
				sql = new StringBuffer(sql.substring(0, endIndex));
			}
		}
		if (orderby != null && orderby.size() > 0) {
			sql.append(" ORDER BY ");
			for (Map.Entry me : orderby.entrySet()) {
				String columnName = me.getKey();
				String columnValue = me.getValue();
				sql.append(columnName).append(" ").append(columnValue)
						.append(",");
			}
			sql = sql.deleteCharAt(sql.length() - 1);
		}
		sql.append(" ) t WHERE ROWNUM<=? ) WHERE rn>=? ");
		System.out.println("SQL=" + sql);
		Object[] args = { pageNo * pageSize, (pageNo - 1) * pageSize + 1 };
		RowMapper rowMapper = BeanPropertyRowMapper.newInstance(entityClass);
		return jdbcTemplate.query(sql.toString(), args, rowMapper);
	}

	private int count(Map where) {
		StringBuffer sql = new StringBuffer(" SELECT COUNT(*) FROM "
				+ simpleName);
		if (where != null && where.size() > 0) {
			sql.append(" WHERE ");
			for (Map.Entry me : where.entrySet()) {
				String columnName = me.getKey();
				String columnValue = me.getValue();
				sql.append(columnName).append(" ").append(columnValue)
						.append(" AND "); // 没有考虑or的情况
			}
			int endIndex = sql.lastIndexOf("AND");
			if (endIndex > 0) {
				sql = new StringBuffer(sql.substring(0, endIndex));
			}
		}
		System.out.println("SQL=" + sql);
		return jdbcTemplate.queryForObject(sql.toString(),Integer.class);
	}

}

连接测试类SpringTest.java

package com.soft.dao;

import java.sql.SQLException;

import javax.sql.DataSource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.soft.entity.Test2;

@RunWith(SpringJUnit4ClassRunner.class)  
@ContextConfiguration(locations = { "classpath:spring/spring-mvc.xml" })
public class SpringTest {
	
	@Autowired  
    private Test2Dao test2Dao;
	
	// 测试是否取得数据库连接  
    @Test  
    public void testDataSource() throws SQLException {  
        @SuppressWarnings("resource")
		ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:spring/spring-mvc.xml");  
        DataSource dataSource = ctx.getBean(DataSource.class);  
        System.out.println(dataSource.getConnection());  
    }  
    
	@Test  
    public void testSave() throws Exception {  
		Test2 test = new Test2();  
		test.setId(1);  
		test.setAreaid("HQ");  
		test.setO("00010002000300040005");  
		test2Dao.save(test);  
    }  
}

在查资料写基类的Service和Controller

写完会把事列传上来的。。。

你可能感兴趣的:(J2EE相关)