CircleSmart的个人博客

一步一个脚印

博客园 首页 新随笔 联系 订阅 管理

BaseAction

public class BaseAction extends ActionSupport {

	protected String target;

	public Map getRequest(){
		return (Map)ActionContext.getContext().get("request");
	}
	
	public Map getSession(){
		return ActionContext.getContext().getSession();
	}
	
	public Map getApplication(){
		return ActionContext.getContext().getApplication();
	}
	
	public HttpServletResponse getResponse(){
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html;charset=utf-8");
		return response;
	}

  DaoFactory

public class DaoFactory<T> {
	private static String fname = "oracle.jdbc.driver.OracleDriver";
	private static String url = "jdbc:oracle:thin:@localhost:1521:orcl";
	private static String user = "scott";
	private static String pwd = "tiger";
	/**
	 * 加载数据库驱动
	 */
	static{
		try {
			Class.forName(fname);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * 创建登陆对象,获取connection
	 * @return
	 */
	public Connection getConnection(){
		try {
			return DriverManager.getConnection(url,user,pwd);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 设置preparedStatement对象参数
	 * @param ps
	 * @param params
	 * @throws SQLException
	 */
	public void setParams(PreparedStatement ps,Object[] params) throws SQLException{
		if(params == null)return;
		for(int i = 0; i < params.length; i++){
			ps.setObject(i+1, params[i]);
		}
	}
	/**
	 * 查询方法
	 * @param sql
	 * @param params
	 * @return
	 */
	public List<List> query(String sql,Object[] params) {
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		ArrayList allData = new ArrayList();
		try {
			con = getConnection();
			pstmt = con.prepareStatement(sql);
			setParams(pstmt,params);
			rs = pstmt.executeQuery();
			int colCount = rs.getMetaData().getColumnCount();
			while (rs.next()) {
				ArrayList rowData = new ArrayList();
				for (int i = 1; i <= colCount; i++) {
					rowData.add(rs.getObject(i));
				}
				allData.add(rowData);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			closeAll(rs,pstmt,con);
		}
		return allData;
	}
	/**
	 * 
	 * @param sql 查询语句,要求句中字段名或别名必须和类中的属性名相同
	 * @param params sql语句所需的参数数组
	 * @param clazz 要封装的类的Class对象
	 * @return 返回封装好的对象,装载在集合中
	 * @throws Exception
	 * 
	 */
	public List<T> list(String sql,Object[] params,Class clazz){
		List<T> list=new ArrayList<T>();
		Connection con=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		try {
			con = getConnection();
			ps = con.prepareStatement(sql);
			setParams(ps, params);
			rs = ps.executeQuery();
			ResultSetMetaData md=rs.getMetaData();
			int colCount=md.getColumnCount();			
			String fieldName="";	
			Field field=null;
			
			while(rs.next()){
				T obj=(T)clazz.newInstance();//实例化包装实体
				for(int i=1;i<=colCount;i++){
					fieldName=md.getColumnName(i);//获得数据库字段名
					//System.out.println("字段名:====================="+ fieldName+"================" + rs.getString(i));
					try {
						field = clazz.getDeclaredField(fieldName);//获得实体类中和数据库字段名相应的Field对象
						field.setAccessible(true);//设置Field的可访问性为true,否则私有属性不能访问	
						//System.out.println("字段类型:===================" + field.getType().getName()+"================");
						field.set(obj, convert(rs.getString(i),field.getType()));
						//调用Field的set方法给属性赋值
					} catch (Exception e) {	//如果没有相应的Field对象则不作任何处理			
						
					}
				}
				list.add(obj);
			}
		} catch (SQLException e) {			
			e.printStackTrace();
		} catch (Exception e) {
			
			e.printStackTrace();
		}finally{
			closeAll(rs, ps, con);
		}
		return list;		
	}
	/**
	 * 该方法用于返回多对一关系的集合
	 * @param sql 用于多表联合查询的语句,要求主类对应的字段前缀名必须和类名相同(不区分大小写),
	 * 引用类对应的字段前缀名必须和主类中引用的属性名相同(大小写严格区分)
	 * @param params 查询语句的参数数组
	 * @param clazzs 返回的封装对象,第一个是List中封装的主对象,其余为该对象的引用属性对象
	 * @return
	 * @throws Exception
	 */
	public List<T> list(String sql,Object[] params,Class...clazzs){
		List<T> list=new ArrayList<T>();
		Connection con=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		try {
			con = getConnection();
			ps = con.prepareStatement(sql);
			setParams(ps, params);
			rs = ps.executeQuery();
			ResultSetMetaData md=rs.getMetaData();
			int colCount=md.getColumnCount();
			System.out.println(colCount);
			String fieldName="";//sql中的字段名或别名
			Field field=null; //要包装的类中的属性对象
			String prefixName="";//数据库字段的前缀名(映射类名)
			Map<String,Object> refMap=new HashMap<String,Object>();//用来存放主类中引用类对象的属性名和对象
			String key="";//用来标记refMap中的键
			while(rs.next()){
				List<T> claObjList=new ArrayList<T>();
				for(Class cla:clazzs){//将要封装的实体类型实例化放入到List中,以便将rs中的值赋值给实例的属性
					claObjList.add((T) cla.newInstance());
				}
				for(int j=0;j<clazzs.length;j++){
					for(int i=1;i<=colCount;i++){
						fieldName=md.getColumnName(i);
						prefixName=fieldName.split("\\.")[0];//获得结果集中字段的前缀名
						fieldName=fieldName.split("\\.")[1];//获得结果集中字段的名称
						//System.out.println(clazzs[j].getSimpleName()+"==="+prefixName+"==="+fieldName+"---");
						if(clazzs[j].getSimpleName().toLowerCase().equals(prefixName.toLowerCase())){
							try {
								//System.out.println(clazzs[j].getSimpleName());
								field=clazzs[j].getDeclaredField(fieldName);//获得当前类中所有的字段对象
								field.setAccessible(true);//设置Field的可访问性为true,否则私有属性不能访问				
								field.set(claObjList.get(j), convert(rs.getString(i),field.getType()));
								//给参数数组对映的实例化对象的属性赋值	
								if(j>0) refMap.put(prefixName, claObjList.get(j));
								//如果是第二个以后的对象,则放入到引用对象的Map中
							} catch (Exception e) {							
								e.printStackTrace();
							}						
						}
					}
					
				}				
				Set<String> keySet=refMap.keySet();
				Iterator<String> it=keySet.iterator();			
				while(it.hasNext()){
					key=it.next();
					try {
						field=clazzs[0].getDeclaredField(key);//获得主类中外键对象的引用字段对象
						field.setAccessible(true);//设置该字段可访问
						field.set(claObjList.get(0), refMap.get(key));//将Map集合中该键对应的值赋值给该字段
					} catch (Exception e) {					
						
					}
				}
				list.add(claObjList.get(0));
			}
		} catch (SQLException e) {			
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			closeAll(rs, ps, con);
		}
		return list;		
	}
	/**
	 * 将传入的字符串参数转化成制定的数据类型,如果格式不匹配则返回null
	 * 
	 * @param <T>
	 * @param param
	 *            要转换的参数字符串
	 * @param clas
	 *            转换的目标CLASS
	 * @return
	 */
	private <T extends Serializable> T convert(String param, Class clas) {
		if (param == null || param == "" || clas == null)
			return null;
		String type = clas.getName();// 获得要转换的数据类型名称
		//System.out.println(type);
		if (type.equals("java.lang.String"))
		{
			//System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
			return (T) param;
		}
		try {// 根据不同类型的属性,返回不同的结果,如果出现异常,则返回null
			if (type.equals("java.util.Date")) {
				return (T) new java.util.Date(java.sql.Timestamp.valueOf(param)
						.getTime());
			}
			if (type.equals("java.sql.Date")) {
				return (T) new java.sql.Date(java.sql.Timestamp.valueOf(param).getTime());
			}
			if (type.equals("java.sql.Timestamp")) {
				return (T) java.sql.Timestamp.valueOf(param);
			}
			if (type.equals("java.lang.Char")) {
				return (T) Character.valueOf(param.charAt(0));
			}
			if (type.equals("java.lang.Integer") || type.equals("int")) {
				return (T) Integer.valueOf(param);
			}
			if (type.equals("java.lang.Double") || type.equals("double")) {
				return (T) Double.valueOf(param);
			}
			if (type.equals("java.lang.Float") || type.equals("float")) {
				return (T) Float.valueOf(param);
			}
			if (type.equals("java.lang.Byte") || type.equals("byte")) {
				return (T) Byte.valueOf(param);
			}
			if (type.equals("java.lang.Short") || type.equals("short")) {
				return (T) Short.valueOf(param);
			}
			if (type.equals("java.lang.Long") || type.equals("long")) {
				return (T) Long.valueOf(param);
			}
			if (type.equals("java.lang.Boolean") || type.equals("boolean")) {
				return (T) Boolean.valueOf(param);
			}
		} catch (Exception e) {
			//e.printStackTrace();
		}
		return null;
	}
	/**
	 * 将sql语句中传入的地段名称转换为相应的set方法名
	 * @param fieldName 传入的sql语句的字段名称
	 * @return 返回set方法名称
	 */
	private String findSetMethodName(String fieldName) {
		Character firstChar = fieldName.charAt(0);
		firstChar = Character.toUpperCase(firstChar);
		String methodName = "set"+firstChar + fieldName.substring(1);// 将首字母小写
		return methodName;
	}
	public boolean updateTrans(String[] sql,List<Object[]> listParam) {
		Connection con = null;
		PreparedStatement pstmt = null;		
		try {
			con = getConnection();
			con.setAutoCommit(false);
			for(int i=0;i<sql.length;i++){				
				pstmt = con.prepareStatement(sql[i]);
				setParams(pstmt,listParam.get(i));
				pstmt.executeUpdate();	
			}
			con.commit();
			return true;
		} catch (Exception e) {			
			e.printStackTrace();
			try {
				con.rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		} finally {
			closeAll(null,pstmt,con);
		}
		return false;
	}
	public int update(String sql,Object[] params) {
		Connection con = null;
		PreparedStatement pstmt = null;		
		try {
			con = getConnection();
			pstmt = con.prepareStatement(sql);
			setParams(pstmt,params);
			return pstmt.executeUpdate();			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			closeAll(null,pstmt,con);
		}
		return -1;
	}
	
	public int update(String sql,Object[] params,Connection con) {
		PreparedStatement pstmt = null;		
		try {
			con = getConnection();
			pstmt = con.prepareStatement(sql);
			setParams(pstmt,params);
			return pstmt.executeUpdate();			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			closeAll(null,pstmt,null);
		}
		return -1;
	}
	
	/**
	 * 修改数据库信息的通用方法
	 * @param sql
	 * 一个sql语句
	 * @param params
	 * 参数数组
	 * @return
	 * 修改每条信息的主键,为int类型
	 */
	public int getKey(String sql,Object[] params) {
		int id=0;
		Connection conn=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		try {
			conn =getConnection();
			ps = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
			setParams(ps, params);
			ps.executeUpdate();
			rs = ps.getGeneratedKeys();
			while(rs.next())
				id=rs.getInt(1);
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	finally{
		closeAll(rs,ps,conn);
		}
		return id;
	}
	/**
	 * 修改数据库信息的通用方法
	 * @param sql
	 * 一个sql语句
	 * @param params
	 * 参数数组
	 * @param con
	 * 一个Connection对象
	 * @return
	 * 修改每条信息的主键,为int类型
	 */
	public int getKey(String sql,Object[] params,Connection con) {
		int id=0;
		PreparedStatement ps=null;
		ResultSet rs=null;
		try {
			con = getConnection();
			ps = con.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
			setParams(ps, params);
			ps.executeUpdate();
			rs = ps.getGeneratedKeys();
			while(rs.next()){
				id=rs.getInt(1);
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	finally{
		closeAll(rs,ps,null);
		}
		return id;
	}
	
	
	/**
	 * 关闭连接对象
	 * @param rs
	 * @param ps
	 * @param con
	 */
	public void closeAll(ResultSet rs, Statement ps, Connection con) {
		// TODO Auto-generated method stub
		try {
			if(rs != null){
				rs.close();
				rs = null;
			}
			if(ps != null){
				ps.close();
				ps = null;
			}
			if(con != null){
				con.close();
				con = null;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	/**
	 * 测试显示数据
	 * @param args
	 */
	public static void main(String[] args){
		DaoFactory dao = new DaoFactory();
		List li = dao.query("select * from rights", null);
		System.out.println(li);
	}
	
}

  

posted on 2017-04-16 16:03  circlesmart  阅读(133)  评论(0编辑  收藏  举报