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 @ 2022-04-08 14:29  南风知君  阅读(548)  评论(0)    收藏  举报