MyBatis:SQL传参

SQL传参有两种形式

 首先在Mapper XML中编写<select>标签并书写SQL语句

复制代码
<!--单参数传参,使用parameterType指定参数的数据类型,SQL中#{value}提取参数-->
    <select id="selectById" parameterType="Integer" resultType="com.MyBatis.entity.Goods">
        select * from t_goods where goods_id = #{value}
    </select>
    <!--多参数传参,使用parameterType指定Map接口,SQL中#{key}提取参数-->
    <select id="selectByPriceRange" parameterType="java.util.Map" resultType="com.MyBatis.entity.Goods">
        select * from t_goods
        where
          current_price between #{min} and #{max}
        order by current_price
        limit 0,#{limt}
    </select>
复制代码

 测试代码

复制代码
//单参数传参
    @Test
    public void testSelectById(){
        SqlSession sqlSession=null;
        try{
            sqlSession=MyBatisUtils.openSession();
            Goods goods = sqlSession.selectOne("goods.selectById", 1603);
            System.out.println(goods.getTitle());
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            MyBatisUtils.closeSession(sqlSession);
        }
    }
    //多参数传参
    @Test
    public void testSelectByPriceRange(){
        SqlSession sqlSession=null;
        try{
            sqlSession=MyBatisUtils.openSession();
            Map param = new HashMap();
            param.put("min",100);
            param.put("max",500);
            param.put("limt",10);
            //MyBatis中允许不增加namespace前缀,但需要保证SQL id是全局唯一的
            List<Goods> list = sqlSession.selectList("selectByPriceRange", param);
            for(Goods g:list){
                System.out.println(g.getTitle()+":"+g.getCurrentPrice());
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            MyBatisUtils.closeSession(sqlSession);
        }
    }
复制代码

 

posted @   南风知君  阅读(518)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示