执行方法

复制代码
 @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的键值必须与占位符中的变量名相同)

 

posted on   na2co3-  阅读(59)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏



点击右上角即可分享
微信分享提示