Mybatis的resultMap返回map问题
短信预约 -IT技能 免费直播动态提醒
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;
}
private static void close(Connection conn, PreparedStatement ps, ResultSet rs) throws Exception {
rs.close();
ps.close();
conn.close();
}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341