JDBC 查询 Map转对象

虽然项目中都夹杂了Hibernate的支持,但是团队开发中,很多人为了编写特殊查询的代码时都使用了JDBC进行查询。JDBC查询后返回的是一个List集合,List中组装的是Map,一个Map就是一个对应的对象。但是接口不能直接返回Map,都是返回的对象,以方便自己和其他人使用,为了转换这个Map,往往写这样的代码:

@SuppressWarnings("unchecked")
public static MS_Mont analyzeMapToMS_Mont(Map map){
	MS_Mont obj = new MS_Mont();
	if(null != map.get("montNo")) obj.setMontNo(Integer.parseInt(map.get("montNo").toString()));
	if(null != map.get("montName")) obj.setMontName(map.get("montName").toString());
	if(null != map.get("montType")) obj.setMontType(Integer.parseInt(map.get("montType").toString()));
	if(null != map.get("montLength")) obj.setMontLength(Integer.parseInt(map.get("montLength").toString()));
	if(null != map.get("montDesc")) obj.setMontDesc(map.get("montDesc").toString());
	if(null != map.get("bigType")) obj.setBigType(Integer.parseInt(map.get("bigType").toString()));
	if(null != map.get("bigTypeName")) obj.setBigTypeName(map.get("bigTypeName").toString());
	if(null != map.get("littleType")) obj.setLittleType(Integer.parseInt(map.get("littleType").toString()));
	if(null != map.get("littleTypeName")) obj.setLittleTypeName(map.get("littleTypeName").toString());
	if(null != map.get("insertTime")) obj.setInsertTime(map.get("insertTime").toString());
	if(null != map.get("updateTime")) obj.setUpdateTime(map.get("updateTime").toString());
	if(null != map.get("userNoRe")) obj.setUserNoRe(Integer.parseInt(map.get("userNoRe").toString()));
	if(null != map.get("userNoLast")) obj.setUserNoLast(Integer.parseInt(map.get("userNoLast").toString()));
	return obj;
}

 

很麻烦,很多,很枯燥。
为了解决这个问题,我列出一个解决方法,写一个方法,传入要赋值的对象和Map,然后根据列的属性名称从Map中获得响应的值,然后赋值给这个对象的属性
例如,这里写了一个简单的查询:

 

public CM_Line getObjectBean(int lineNo) {
	try {
		String sql = "select * from cm_line where lineNo=?";
		Object[] obj = new Object[]{ lineNo };
		List rows = jdbcTemplate.queryForList( sql, obj );
		if(null != rows && rows.size() > 0) {
			CM_Line line = new CM_Line();
			return (CM_Line) line.analyzeMap((Map)rows.get(0));
		} else {
			return null;
		}
	} catch (Exception e) {
		logger.error(e);
	}
	return null;
}

 

然后我们调用了他的analyzeMap方法,这个方法把当前对象当作要赋值的对象,然后调用公用方法进行组装:

public Object analyzeMap(Map<String, Object> para){
	Object obj = this;
	ObjectUtil.setValToObj(obj, para);
	return obj;
}

 

公用方法:

public synchronized static void setValToObj(Object entityName, Map<String, Object> para){
	try {
		Class c = entityName.getClass();
		// 获得对象属性   
        Field field[] = c.getDeclaredFields();
        for (Field f : field) { 
        	try {
        		PropertyDescriptor pd = new PropertyDescriptor(f.getName(), c);  
                Method writeMethod = pd.getWriteMethod();
                if(!CommonCheck.isNullOrEmpty(para.get(f.getName())))
                	writeMethod.invoke(entityName, para.get(f.getName()));
			} catch (Exception e) {
			}
        }
	} catch (Exception e) {
	}
}

 

下面就有人说了,那根据对象获得这个对象的Map怎么搞,这个之前已经写过了,不这里仍然把代码放一下:

/**    
 * 返回一个对象的属性和属性值
 */     
public synchronized static LinkedHashMap<String,String> getProAndValMap(Object entityName) {    
	LinkedHashMap<String,String> map = new LinkedHashMap<String, String>();   
    try {   
        Class c = entityName.getClass();   
        // 获得对象属性   
        Field field[] = c.getDeclaredFields();      
        for (Field f : field) {
            Object v = invokeMethod(entityName, f.getName(), null);   
            if(null != v) map.put(f.getName(), v.toString());
            else  map.put(f.getName(), "");
        }   
    } catch (Exception e) {   
        map = null;   
    }   
    return map;   
}
/**
 * 获得对象属性的值
 */
private synchronized static Object invokeMethod(Object owner, String methodName,
		Object[] args) throws Exception {
	Class ownerClass = owner.getClass();
	methodName = methodName.substring(0, 1).toUpperCase() + methodName.substring(1);
	Method method = null;
	try {
		method = ownerClass.getMethod("get" + methodName);
	} catch (Exception e) {
	}
	return method.invoke(owner);
}

 

请您到ITEYE网站看原创,谢谢!

http://cuisuqiang.iteye.com/ ! 

自建博客地址:http://www.javacui.com/ ,内容与ITEYE同步!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JDBC是Java数据库连接的一种技术,通过它可以连接数据库并执行SQL语句进行数据的增删改查。当使用JDBC查询数据库后,可以将查询结果赋值给一个Map对象。 首先,我们需要导入JDBC相关的包,并在代码中实例化JDBC的连接对象。然后,我们可以使用连接对象创建一个Statement对象,通过它执行SQL查询语句。查询的结果会返回一个ResultSet对象,其中包含了从数据库中检索到的数据。 接下来,我们可以使用ResultSet对象的方法来遍历查询结果,并将查询的数据放入一个Map对象中。可以使用ResultSet的方法获取每一条记录的字段值,然后将字段名和对应的字段值存入Map中。可以使用put方法将字段名作为键,字段值作为值存入Map中。 下面是一个示例代码: ```java import java.sql.*; import java.util.HashMap; import java.util.Map; public class JDBCTest { public static void main(String[] args) { // JDBC连接数据库的代码 try { // 创建连接对象 Connection connection = DriverManager.getConnection("jdbc:数据库类型://数据库地址:端口号/数据库名称", "用户名", "密码"); // 创建Statement对象 Statement statement = connection.createStatement(); // 执行SQL查询语句,返回ResultSet对象 ResultSet resultSet = statement.executeQuery("SELECT * FROM 表名"); // 创建Map对象,用于存储查询结果 Map<String, Object> resultMap = new HashMap<String, Object>(); // 遍历查询结果 while (resultSet.next()) { // 获取字段名和字段值并放入Map中 resultMap.put("字段名1", resultSet.getObject("字段名1")); resultMap.put("字段名2", resultSet.getObject("字段名2")); // ... } // 打印Map中的数据 for (Map.Entry<String, Object> entry : resultMap.entrySet()) { System.out.println("字段名:" + entry.getKey() + ",字段值:" + entry.getValue()); } // 关闭连接等资源 } catch (SQLException e) { e.printStackTrace(); } } } ``` 这样,经过上述步骤,我们将数据库查询结果存入了一个Map对象中,可以根据需要使用这些数据进行进一步的操作和处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值