MyBatis——案例——查询-查询所有
查询-查询所有数据
1、创建相应Mapper接口文件 以及Mapper配置信息文件
      
  
修改配置文件中 namespace :
       
2、编写接口方法:Mapper 接口
参数:无
结果:List<Brand>
      
3、编写SQL语句(接口文件中按Alt+回车快速编写)
      
4、执行方法,测试
(1)获取 SQLSessionFactory 对象
 //1、获取 SqlSessionFactory 对象
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
(2)获取 SQLSession 对象
        // 2、获取 SQLSession 对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
(3)获取Mapper接口代理对象
        // 3、获取Mapper接口代理对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
(4)执行方法
        // 4、执行方法
        List<Brand> brands = brandMapper.selectAll();
            // 打印
        System.out.println(brands);
(5)释放资源
        // 5、释放资源
        sqlSession.close();
(6)运行结果
        
发现brandName 和 companyName 显示为 null
原因:数据库表的字段名称(下划线命名法) 和 实体类的属性名称(驼峰命名法) 不一样 ,则不能自动封装数据
解决方案:
* 起别名 :对不一样的列名起别名,让别名和实体类的属性名一样
    <select id="selectAll" resultType="com.cqupt.pojo.Brand">
        select id, brand_name brandName, company_name companyName, orderd, description, status
        from tb_brand;
    </select>
起别名之后显示正常:
              
* 缺点:每次都要定义一次别名 如果查询次数过多 显示一长串不美观
* 采用 sql片段
    <!--sql片段-->
    <sql id="brand_column">
        id, brand_name brandName, company_name companyName, orderd, description, status
    </sql>
    <select id="selectAll" resultType="com.cqupt.pojo.Brand">
        select
            <include refid="brand_column"></include>
        from tb_brand;
    </select>
* 缺点:不灵活
最多使用的方法:resultMap 映射
<!--
        id :唯一标识
        type :映射的类型  支持别名
    -->
    <resultMap id="brandResultMap" type="com.cqupt.pojo.Brand">
        <!--
            id :主键字段的映射
                column :表的列名
                property :实体类的属性名
            result :一般字段的映射
                column :表的列名
                property :实体类的属性名
        -->
        <!-- 这里仅需完成对一般字段映射 所以使用的result -->
        <result column="brand_name" property="brandName" />
        <result column="company_name" property="companyName" />
    </resultMap>
    <select id="selectAll" resultMap="brandResultMap">
        select
        *
        from tb_brand;
    </select>

                
            
        
浙公网安备 33010602011771号