您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
09-查询-条件查询(散装参数,POJO对象参数,Map参数)
发布时间:2024-11-21 12:40:55编辑:雪饮阅读()
-
散装参数
首先假如我有status、company_name,brand_name多个参数要进行查询,尤其后面两个参数是模糊查询,则mapper中select标签内容可以写成这样
<select id="selectByCondition" resultMap="brandResultMap">
select * from tb_brand where status=#{status} and company_name like #{companyName} and brand_name like #{brandName}
</select>
为什么这么不包含%,因为第一个%号前面与关闭的%后面都是有单引号或双引号的。
在这里使用了#占位符号的时候相当于预处理,而这里预处理里面这样操作是不行的,为什么不行,我也说不上上来,反正用$非预处理的时候就可以。所以这里我是将%也放在参数内容里面的。
那么mapper接口中对该方法的抽象方法定义如
List<Brand> selectByCondition(@Param("status") int status,@Param("companyName") String companyName,@Param("brandName") String brandName);
Param注解值为参数占位名,而形参名称就不用多说了。
那么我们的测试方法则如
public void test3() 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);
int status=0;
String companyName="松鼠";
String brandName="松鼠";
List<Brand> brands=brandMapper.selectByCondition(status,"%"+companyName+"%","%"+brandName+"%");
System.out.println(brands);
sqlSession.close();
}
对象参数
mapper中的statement的sql还是保持不变。
而抽象方法可以同名重载一个我们POJO实例的形参如
List<Brand> selectByCondition(Brand brand);
那么我们的测试方法如:
@Test
public void test4() 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);
int status=0;
String companyName="松鼠";
String brandName="松鼠";
Brand brand=new Brand();
brand.setStatus(status);
brand.setBrandName("%"+brandName+"%");
brand.setCompanyName("%"+companyName+"%");
List<Brand> brands=brandMapper.selectByCondition(brand);
System.out.println(brands);
sqlSession.close();
}
map参数
除了用POJO实例本身作为参数,还可以使用HashMap进行重载该方法。
则mapper接口的抽象方法如
List<Brand> selectByCondition(Map map);
而测试方法如
@Test
public void test4() 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);
int status=0;
String companyName="松鼠";
String brandName="松鼠";
Map map=new HashMap();
map.put("status",status);
map.put("brandName","%"+brandName+"%");
map.put("companyName","%"+companyName+"%");
List<Brand> brands=brandMapper.selectByCondition(map);
System.out.println(brands);
sqlSession.close();
}
关键字词:条件查询,散装参数,对象参数,Map参数
相关文章
-
无相关信息