欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Mybatis的resultMap返回map问题

程序员文章站 2022-06-16 20:42:05
目录resultmap返回map问题简单封装resultmap返回对象为mapresultmap返回map问题

resultmap返回map问题

<resultmap type="map" id="bankmaintainmap">
      <result column="bank_name" property="bankname"/>
      <result column="maintain_time_interval" property="maintaintimeinterval"/>
  </resultmap>
  <select id="getmaintainnotice" parametertype="map" resultmap="bankmaintainmap">
      select 
          bank_name,
          maintain_time_interval
      from
          fp_channel_prd_bank
      where 
          channel_prd_id=7 
      and     
          maintain_time_interval
  </select>

简单封装resultmap返回对象为map

public class dbutils {
    private static string host = "47.93.******";
    private static string port = "3306";
    private static string username = "*****";
    private static string password = "******";
    private static string database = "******";
    static {
        try {
            class.forname("com.mysql.jdbc.driver");
        } catch (exception e) {
        }
    }
    private static connection getconn() {
        connection conn = null;
        try {
            string url = "jdbc:mysql://" + host + ":" + port + "/" + database;
            conn = drivermanager.getconnection(url, username, password);
        } catch (exception e) {
            e.printstacktrace();
        }
        return conn;
    }
    public static list<map<string, object>> execquery(string sql, object[] args) throws exception {
        connection conn = getconn();
        preparedstatement ps = conn.preparecall(sql);
        resultset rs = null;
        int count = stringutils.countmatches(sql, "?");
        //变量赋值。。。。。。
        for (int i = 0; i < count; i++) {
            ps.setobject(i, args[i]);
        }
        list<map<string, object>> list = new arraylist<map<string, object>>();
        rs = ps.executequery();
        resultsetmetadata metadata = rs.getmetadata();
      //注意。。metadata.getcolumnname 获取字段名,rs.getobject 获取属性 是从 1 开始的,而不是从0 开始
        while (rs.next()) {
            int rowsize = metadata.getcolumncount();
            map<string, object> map = new hashmap<>();
            for (int i = 1; i <= rowsize; i++) {
                string labelname = metadata.getcolumnname(i);
                object obj = rs.getobject(labelname);
                map.put(labelname, obj);
            }
            list.add(map);
        }
        close(conn, ps, rs);
        return list;
    }
    /**
     * @param conn
     * @param ps
     * @param rs
     * @throws exception
     */
    private static void close(connection conn, preparedstatement ps, resultset rs) throws exception {
        rs.close();
        ps.close();
        conn.close();
    }

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。