spring中的RowMapper
生活随笔
收集整理的這篇文章主要介紹了
spring中的RowMapper
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2019獨角獸企業重金招聘Python工程師標準>>>
一.簡介
sql中返回的是自定義的列或者一些統計的列,直接用hibernate無法處理;
此時,可以使用RowMapper,將數據中的每一行數據封裝成用戶定義的類
二.RowMapper
1、方法:
建立內部類實現RowMapper接口;
RowMapper中有一個mapRow方法,所以實現RowMapper接口一定要實現mapRow方法;
對自定義類的包裝就在mapRow方法中實現.
2、例子:
public?class?TestDao?{ private?JdbcTemplate?jt; public?void?setJt(JdbcTemplate?jt)?{this.jt?=?jt; } public?List<TNpc>?getAll(){String?sql?=?"select?*?from?t_npc";//使用List?list?=?jt.query(sql,?new?NpcRowMapper());return?list; } /** *?定義內部類實現RowMapper接口 */ public?class?NpcRowMapper?implements?RowMapper{//實現mapRow方法public?Object?mapRow(ResultSet?rs,?int?num)?throws?SQLException?{//對類進行封裝TNpc?npc?=?new?TNpc();npc.setId(rs.getLong("id"));npc.setName(rs.getString("name"));return?npc;}??} }三.相同效果的其他方法:map映射
用map映射相對rowMapper更簡單,且無需建接口
List<Object>?args?=?new?ArrayList<Object>(); args.add(before); args.add(today); //sql獲取需要的統計字段 String?sql?=?"select?cur_week_answer_count,cur_week_answer_score?from?t_answer?where?create_time>??and?create_time<??and?is_best_answer!=1"; //queryForList,然后把獲取到的數據放到map中 List<Map<String,Object>>?ids?=?EnvUtils.getEnv().getSimpleJdbcTemplate().queryForList(sql.toString(),?args.toArray()); if(ids?!=?null?&&?!ids.isEmpty()){ for(Map<String,Object>?map?:?ids){ //從map中獲取數據 long?answerCount?=?Long.parseLong(String.valueOf(map.get("cur_week_answer_count"))); long?answerScore?=?Long.parseLong(String.valueOf(map.get("cur_week_answer_score?"))); Answer?answer?=?answerService.load(answerCount,answerScore); Question?question?=?answer.getQuestion(); if(answer?!=?null?&&?question?!=?null?&&?answer.getId()?==?question.getBestAnswerId()){ qustionRaltionZhidaoService.setBestAnswerToZhidao(answer); } } }轉載于:https://my.oschina.net/xsh1208/blog/176507
總結
以上是生活随笔為你收集整理的spring中的RowMapper的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Erlang列表操作里面的变量绑定规则
- 下一篇: 动态子类化CComboBox以得到子控件