
List
// 使用该接口的代理对象,调用其接口方法,接口方法有对应的配置文件XML,
// XML文件中有对应的sql语句,可以执行,查询到的结果返回有个 集合
package com.itheima.mapper;import com.itheima.pojo.Brand;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import org.junit.Test;import java.io.IOException;import java.io.InputStream;import java.util.List;public class MyBatisTest {@Testpublic void testSelectAll() throws Exception {// 1. 获取SqlSessionFactory// 1. 加载mybatis的核心配置文件,获取SqlSessionFactory// 1. 加载mybatis的核心配置文件,获取SqlSessionFactory (sql会话工厂)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);// 将该接口的的class对象,传进去,就可以获得该借口的代理对象// 4. 执行方法:List<Brand> brands = brandMapper.selectAll(); // 使用该接口的代理对象,调用其接口方法,接口方法有对应的配置文件XML,// XML文件中有对应的sql语句,可以执行,查询到的结果返回有个 集合<Brand>对象System.out.println(brands); // 打印集合对象,查看其存储的Brand类对象// 5. 释放资源sqlSession.close();}}
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><!--Mapper是映射的意思namespace:名称空间--><mapper namespace="com.itheima.mapper.BrandMapper"><!--数据库表的字段名称 和 实体类的属性名称 不一样,则不能自动封装数据解决方法:* 起别名: 对不一样的列名* 缺点: 每次查询都要定义一次别名* sql 片段* 缺点:不灵活* resultMap:1. 定义<resultMap>标签2. 在<select>标签中,使用resultMap属性替换,resultType属性--><!--id: 唯一标识type: 映射的类型,支持别名--><resultMap id="brandResultMap" type="brand"><!-- 这个是column是列名(也可以叫字段名,property)叫属性名 --><!--id: 完成主键字段的映射column: 表的列名property: 实体类的属性名result: 完成一般字段的映射column: 表的列名property: 实体类的属性名--><result column="brand_name" property="brandName" /><result column="company_name" property="companyName" /></resultMap><select id="selectAll" resultMap="brandResultMap">select*from tb_brand;</select><!--sql片段--><!-- <sql id="brand_column"> -- 这里是标明 brand类的字段全部用sql片段代替--><!-- id, brand_name as brandName, company_name as companyName, ordered, description, status--><!-- </sql>--><!-- <select id="selectAll" resultType="com.itheima.pojo.Brand">--><!-- <!–在这里面写查询语句 –>--><!-- select--><!-- <include refid="brand_column"></include>--><!-- from tb_brand;--><!-- </select>--><!-- <select id="selectAll" resultType="com.itheima.pojo.Brand">--><!-- <!–在这里面写查询语句 –>--><!-- select id, brand_name as brandName, company_name as companyName, ordered, description, status--><!-- from tb_brand;--><!-- </select>--><!-- <select id="selectAll" resultType="com.itheima.pojo.Brand">--><!-- <!–在这里面写查询语句 –>--><!-- select *--><!-- from tb_brand;--><!-- </select>--></mapper>
