执行方法
@Test public void testSelectBycondition() throws IOException { //接收变量 int status = 0; String company_name = "华为"; String brand_name = "华为"; //处理数据 company_name = "%" + company_name + "%"; brand_name = "%" + brand_name + "%"; //1、获取sqlSessionFactory String rescource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(rescource); 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.selectBycondition(status,company_name,brand_name); System.out.println(brands); //5、释放资源 sqlSession.close(); } }
sql映射文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!--namespace:名称空间。写接口给的全类名,相当于告诉MyBatis这个配置文件是实现哪个接口的。--> <mapper namespace="com.avb.Mapper.BrandMapper"> <!--resultType=""指定查询数据封装结果的时候使用自定义封装规则--> <select id="selectAll" resultType="brand"> select * from tb_brand; </select> <select id="selectByid" resultType="brand"> select * from tb_brand where id = #{id}; </select> <select id="selectBycondition" resultType="brand"> select * from tb_brand where status = #{status} and company_name like #{company_name} and brand_name like #{brand_name}; </select> </mapper>
Mapper接口文件
package com.avb.Mapper; import com.avb.pojo.Brand; import com.avb.pojo.User; import org.apache.ibatis.annotations.Param; import java.util.List; public interface BrandMapper { //查询所有 List<Brand> selectAll(); //按照id查询 Brand selectByid(int id); //按照多种条件查询 List<Brand> selectBycondition(@Param("status")int status,@Param("company_name")String company_name,@Param("brand_name")String brand_name); }
*映射文件占位符变量和接口文件中的变量名应该相同
另外两种接口方法
map
(*map的键值必须与占位符中的变量名相同)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏