Mybatis如何從數據庫中獲取數據存為List類型(存為model)

從數據庫中獲取數據存為List類型(存為model)

從數據庫中獲取的數據,存到一個model中,需要註意兩點。

  • 一、在dao中,隻能用List類型接受結果
  • 二、要在mapper中寫清楚resultType
//DAO 
@Override 
public ArrayList<YourModel> getMainInfo(int id) { 
    // TODO Auto-generated method stub 
    List<YourModel> result = null; 
    try{ 
        sqlSession = this.getSqlSession(); 
    }catch (Exception e){ 
        e.printStackTrace(); 
        YourModel yourModel = new YourModel(); 
        try{ 
          /** 
            * 很奇怪,在這裡不能直接強轉類型為ArrayList<GradeCheck> 
            * 隻能在下面return的時候強轉類型..... 
            * */ 
            result = sqlSession.selectList(this.NAMESPACE.concat("getMainInfo"), yourModel); 
    }catch (Exception e){ 
    return null; 
    } 
    return (ArrayList<YourModel>)result; 
}
//mapper
List<model> findByIds(Long... ids); 
<select id="findByIds" resultMap="BaseResultMap"> 
    select <include refid="Base_Column_List" /> from model(tableName) 
    where ID in 
    <foreach item="item" index="index" collection="array" open="(" separaotr="," close=")"> 
    #{item} 
    </foreach> 
</select>

Mybatis存儲List類型數據

Dao層

void insertList(List<TZpcjsj> list);

*Mapper

 <!--批量 插入記錄 -->
    <insert id="insertList" >
        INSERT INTO t_zpcjsj(nian_fen,hang_hao,belong_to_account,zhong_ming,lai_yuan,chang_du,bi_qiang,ma_zhi,ling_zhong,yi_fen,chu_miao_qi,kai_hua_qi,tu_xu_qi,szs_miao_qi,szs_hua_qi,zqd_miao_qi,zqd_hua_qi,shou_huo_zhu_shu,zytx_zhu_xing,zytx_ye_xing,zytx_ling_xing,zytx_zhu_gao,zytx_jie_ling_xing,zytx_ye_xu_xing,ku_wei_bing_zhi,huang_wei_bing_zhi,tian_jian_jue_xuan,mark)VALUES
        <foreach collection="list" item="item" index="index" separator=','>
                (#{item.nianFen},#{item.hangHao},#{item.belongToAccount},#{item.zhongMing},#{item.laiYuan},#{item.changDu},#{item.biQiang},#{item.maZhi},#{item.lingZhong},#{item.yiFen},#{item.chuMiaoQi},#{item.kaiHuaQi},#{item.tuXuQi},#{item.szsMiaoQi},#{item.szsHuaQi},#{item.zqdMiaoQi},#{item.zqdHuaQi},#{item.shouHuoZhuShu},#{item.zytxZhuXing},#{item.zytxYeXing},#{item.zytxLingXing},#{item.zytxZhuGao},#{item.zytxJieLingXing},#{item.zytxYeXuXing},#{item.kuWeiBingZhi},#{item.huangWeiBingZhi},#{item.tianJianJueXuan},#{item.mark})
        </foreach>
    </insert>

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: