SQL传参
技巧:
1.SQL代码部分,先在Navicat中写好并测试代码
2.Java代码部分,可以直接复制以下基础代码,在此基础上增加功能
@Test
public void test(){
SqlSession sqlSession=null;
try {
sqlSession= MyBatisUtils.openSession();
List<Goods> list = sqlSession.selectList("goods.selectAll");
for (Goods g:list){
System.out.println(g.getTitle());
}
} catch (Exception e) {
throw new RuntimeException(e);
}finally {
MyBatisUtils.closeSession(sqlSession);
}
}
1.传单个参数--参数类型为Integer
<select id="selectById" parameterType="Integer" resultType="com.imooc.mybatis.entity.Goods">
SELECT *
FROM `t_goods`
WHERE goods_id = #{value}
</select>
@Test
public void selectById(){
SqlSession sqlSession=null;
try {
sqlSession= MyBatisUtils.openSession();
List<Goods> list = sqlSession.selectList("goods.selectById", 739);
for (Goods g:list){
System.out.println(g.getTitle());
}
} catch (Exception e) {
throw new RuntimeException(e);
}finally {
MyBatisUtils.closeSession(sqlSession);
}
}
2.传多个参数--参数类型为java.util.Map--Java类中直接加入param即可(提前写好内容)
<select id="selectByPrice" parameterType="java.util.Map" resultType="com.imooc.mybatis.entity.Goods">
SELECT *
FROM `t_goods`
WHERE current_price BETWEEN #{min} AND #{max}
LIMIT #{limt}
</select>
@Test
public void selectByPrice(){
SqlSession sqlSession=null;
try {
sqlSession= MyBatisUtils.openSession();
Map param=new HashMap();
param.put("min",100);
param.put("max",200);
param.put("limt",10);
List<Goods> list = sqlSession.selectList("goods.selectByPrice", param);
for (Goods g:list){
System.out.println(g.getTitle());
}
} catch (Exception e) {
throw new RuntimeException(e);
}finally {
MyBatisUtils.closeSession(sqlSession);
}
}