Mybatis resultMap返回map
如果屈原会编程 人气:2resultMap返回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(); }
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
加载全部内容