首页 > 代码库 > 获取单条记录的统一模板

获取单条记录的统一模板

/**
	 * 获取单条记录
	 * @param jdbcTemplate
	 * @param tableName
	 * @param columnsAndValues
	 * @return
	 */
	public T getOne(JdbcTemplate jdbcTemplate,String tableName,Class className,String columnset,
			Map<String,Object> wheres,
			Map<String,String> orders){
		T o = null;
		StringBuffer sql = new StringBuffer();
		sql.append("select "+ columnset + " from "  + tableName + " where 1=1");
		Object[] values = null;
		if(wheres!=null){
			Set<String> whereConditions = wheres.keySet();
			int size = whereConditions.size();		
			if(size>0){
				values = new Object[size];		
				int i=0;
				for(String c :whereConditions){
					values[i]=wheres.get(c);
					sql.append(" and "+c+"=?");
					i++;
				}
			}
		}
		
		if(orders!=null){
			sql.append("order by ");
			Set<String> orderCols = orders.keySet();
			int size = orderCols.size();
			if(size>0){
				int i = 0;
				for(String c :orderCols){
					i++;
					if(i<size){
						sql.append(c + " " + orders.get(c) + ",");
					}else{
						sql.append(c + " " + orders.get(c));
						break;
					}				
				}				
			}			
		}
			
		System.out.println("getone="+sql.toString());
		List<T> list = jdbcTemplate.query(sql.toString(),
				new BeanPropertyRowMapper<T>(className),values);
		if(list!=null && list.size()>0){
			o = list.get(0);
		}
		list = null;
		wheres = null;
		orders = null;
		sql = null;
		return o;
	}

  

获取单条记录的统一模板