问题:用户在进行查询的时候,可能有的选项并没有填,如果直接进行查询的话是查不出来的,所以这里需要进行改进。
BrandMapper.xml
if:条件判断
test:逻辑表达式
问题1:如果同时没有了status和brandName,会报错:
原因是这里多了一个and
解决方案:多加一个恒等式,然后全体加and
但其实mybatis已经有了非常完美的解决方案——使用< where >标签,替换where关键字。
@Test
public void testSelectByConditionSingle() throws IOException {
// 接收参数
int status = 1;
String companyName = "华为";
String brandName = "华为";
// 为模糊匹配like处理参数
companyName = "%" + companyName + "%";
brandName = "%" + brandName + "%";
//封装对象
Brand brand = new Brand();
// brand.setBrandName(brandName);
// brand.setCompanyName(companyName);
// brand.setStatus(status);
//1、获取sqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2、获取sqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//3、获取Mapper接口的代理对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
//4、执行方法
List<Brand> brands = brandMapper.selectByConditionSingle(brand);
System.out.println(brands);
//释放资源
sqlSession.close();
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)