007.SQL传参(动态传入参数)

1.形式

 

 

 

2.  单参数传递,使用parameterType指定参数的数据类型即可,SQL中#{value}提取参数parameterType="Integer"

2.1 goods.xml

 <!-- 单参数传递,使用parameterType指定参数的数据类型即可,SQL中#{value}提取参数-->
    <select id="selectById" parameterType="Integer" resultType="com.imooc.mybatis.entity.Goods">
        select * from t_goods where  goods_id = #{value}
    </select>

2.2 测试语句

复制代码
 /**
     * 传递单个SQL参数
     *
     * @throws Exception
     */
    @Test
    public void testSelectById() throws Exception
    {
        SqlSession session = null;
        try
        {
            session = MyBatisUtils.openSession();
            Goods goods = session.selectOne("goods.selectById", 1609);//1603代表传入的参数
            System.out.println(goods.getTitle());
        }
        catch (Exception e)
        {
            throw e;
        }
        finally
        {
            MyBatisUtils.closeSession(session);
        }
    }
复制代码

 

3.多参数传递时,使用parameterType指定Map接口,SQL中#{key}提取参数 ,查询价格的范围parameterType="java.util.Map"

3.1 goods.xml

<!-- 多参数传递时,使用parameterType指定Map接口,SQL中#{key}提取参数 -->
    <select id="selectByPriceRange" parameterType="java.util.Map" resultType="com.imooc.mybatis.entity.Goods">
        select * from t_goods
        where
            current_price between  #{min} and #{max}
        order by current_price
        limit 0,#{limt}
    </select>

3.2 测试语句

复制代码
   /**
     * 传递多个SQL参数
     *
     * @throws Exception
     */
    @Test
    public void testSelectByPriceRange() throws Exception
    {
        SqlSession session = null;
        try
        {
            session = MyBatisUtils.openSession();
            Map param = new HashMap();
            param.put("min", 100);
            param.put("max", 500);
            param.put("limt", 10);
            List<Goods> list = session.selectList("goods.selectByPriceRange", param);
            for (Goods g : list)
            {
                System.out.println(g.getTitle() + ":" + g.getCurrentPrice());

            }
        }
        catch (Exception e)
        {
            throw e;
        }
        finally
        {
            MyBatisUtils.closeSession(session);
        }
    }
复制代码

 

posted @   李林林  阅读(1533)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
历史上的今天:
2021-11-23 034.结构伪类选择器(伪类是 W3C 制定的一套选择器的特殊状态,通过伪类您可以设置元素的动态状态,例如悬停(hover)、点击(active)以及文档中不能通过其它选择器选择的元素(这些元素没有 ID 或 class 属性),例如第一个子元素(first-child)或者最后一个子元素(last-child))
点击右上角即可分享
微信分享提示