您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
08-查询-查看详情(mybatis的mapper接收参数的处理)
发布时间:2024-11-20 21:43:06编辑:雪饮阅读()
-
mapper接收参数
mapper中的sql如果要接收参数,例如id。
可以这样写
<select id="selectById" resultMap="brandResultMap">
select * from tb_brand where id=#{id};
</select>
这里#{}是参数占位符。
该参数占位符是以预处理形式的。
当然还有一种占位符是${},这种就纯占位符了,不会做预处理的。
那么我们的mapper接口中的实现则如
package com.mapper;
import POJO.Brand;
import java.util.List;
public interface BrandMapper {
List<Brand> selectAll();
//这里不需要写public,接口里面默认是public
Brand selectById(int id);
}
然后我们的测试方法则如
@Test
public void test2() throws IOException {
String resource="mybatis-config.xml";
InputStream inputStream= Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession=sqlSessionFactory.openSession();
BrandMapper brandMapper=sqlSession.getMapper(BrandMapper.class);
List<Brand> brands=brandMapper.selectAll();
if(brands.size()>0){
Brand brand=brandMapper.selectById(brands.get(0).getId());
System.out.println(brand);
}
sqlSession.close();
}
select标签的parameterType
parameterType属性用来设置接收参数的类型,如
<select id="selectById" parameterType="int" resultMap="brandResultMap">
select * from tb_brand where id=${id};
</select>
当然,这个一般是可以不用写的。
处理sql中的特殊符号
sql中有时候需要用到特殊符号,比如小于号,由于这mapper配置文件是xml,所以小于符号正好是xml的开标签符号。
那么可以使用实体引用来代替,如<,当然这里他们称之为转义。
当然也可以用CDATA实现,在IntelliJ IDEA中在这个mapper配置文件中在这个select标签里面输入CD就会有提示,按照提示的可操作项点击下就快速产生了CDATA结构。那么使用CDATA结构后如
<select id="selectById" parameterType="int" resultMap="brandResultMap">
select * from tb_brand where id <![CDATA[
<
]]>${id};
</select>
CDATA更方便一些,因为这里不仅是小于号,CDATA里面可以输入多个字符,完全当纯字符串处理了。
关键字词:mapper,mybatis,参数