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);
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!