MyBatis 获取参数与返回值结果集映射 总结

MyBatis 获取参数与返回值结果集映射 总结:

搭配环境:SpringBoo+MySql:

定义一个表Employee:

在这里插入图片描述

配置文件配置:

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource # 连接池指定 springboot2.02版本默认使用HikariCP 此处要替换成Druid
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql:///mybatis?serverTimezone=Asia/Shanghai&characterEncoding=utf-8
    username: root
    password: root
    druid: #企业开发中可能会用到的配置
      initial-size: 5 # 初始化时建立物理连接的个数
      min-idle: 5 # 最小连接池连接数量,最小空闲数量
      max-active: 20 # 最大连接池连接数量,最大活跃连接数
      max-wait: 60000 # 配置获取连接等待超时的时间
      timeBetweenEvictionRunsMillis: 60000
      minEvictableIdleTimeMillis: 300000
      validationQuery: SELECT 1
      testWhileIdle: true
      testOnBorrow: true
      testOnReturn: false
      poolPreparedStatements: true
      maxPoolPreparedStatementPerConnectionSize: 20
      filters: stat,wall
      connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
      stat-view-servlet: # 德鲁伊连接池,内置提供一个web版的性能监控配置
        allow: 0.0.0.0 # 允许哪些IP访问druid监控界面,多个IP以逗号分隔
        login-username: root # 设置登录帐号
        login-password: root # 设置登录密码
        reset-enable: false # 是否允许重置数据
        # url-pattern: /database/* # 默认访问根路径是:/druid/;也可以自定义设置
# mybatis配置
mybatis:
  configuration:
   # map-underscore-to-camel-case: true #开启驼峰字段转换
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 设置控制台输入执行的sql语句
  type-aliases-package: cn.js.domain #扫描实体类所在的包

server:
  port: 8080

开启设置控制台输入执行的sql语句:

# mybatis配置
mybatis:
  configuration:
   
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 设置控制台输入执行的sql语句
  type-aliases-package: cn.js.domain #扫描实体类所在的包

一、获取参数:

(1)、单个参数:

1.定义mapper接口:

public interface MybatisTestMapper {
    
    

    Employee selectAone(Long id);
}

2.在mapper.xml文件编写Sql语句:

在要射文件中,要执行CRUD操作有对应的标签
#         id: 指定mapper接口中对应的方法,作用就是使得SQL语句与mapper接口的方法产生关系,一对一对应;
# resultTupe: 定查询出来的教据,封装到那个类型中,可以是对象的全限定名,也可以是其他类型;

在这里插入图片描述

3.测试:

 /**
        *
        * @description: 获取单个参数
        * @param:
        * @retuen:
        **/
        @Test
        public void test01(){
    
    
            Employee employee = mybatisTestMapper.selectAone(1L);
            System.out.println(employee);
        }

4.结果:

在这里插入图片描述

(2)、多个参数:

1.定义mapper接口:

Employee selectAtwo(Long id, String name);

2.在mapper.xml文件编写Sql语句:

<select id="selectAtwo" resultType="cn.js.domain.Employee">
        select * from employee where id=#{id} and name=#{name}
</select>

3.测试:

/**
           *
           * @description: 通过多个参数查询
           * @param:
           * @retuen:
           **/

         @Test
         public void test02(){
    
    
             Employee employee = mybatisTestMapper.selectAtwo(1L,"雄霸");
             System.out.println(employee);
         }

注意:

如果,MapperXml文件中的参数名和mapper接口里面的参数列表没有一 一对应会报错

列:
<select id="selectAtwo" resultType="cn.js.domain.Employee">
        select * from employee where id=#{age} and name=#{tm}
</select>

在这里插入图片描述

原因:

原困:[name,id,param1,poram2],因为我们传递了两个参数,MyBotis会将两个参数以两组Key、VaLue进行存储;
注意:
   在MYBatis中,当参数为多个时,MuBotis会将多个参数值封装到一个Map中
   Map<String,0bject> map = new HashMape>();
 值:1L,"雄霸"
map.put("name","雄霸");
map.put("id",1L);

map.put("param1","雄霸");
map.put("param2",1L);

所以:
该报错的原因是: mybatis底层帮我们把传递的参数,他们封装成了一个map集合,如果我们并没有指出key是多少时,Mybatis
就会以默认的值作为key,即param1,param2作为默认的key,而在map xml文件当中,我们在'#'号所对应的花括号里面的值就是相应的key,但是此时的key又与mymybatis所默认的key不同,所以就找不到myabatis创建的Map相应的key所对应的值value,因此就会爆出SQL语句错误.如果我们测试以他们的param1,param2,或者:name,id 作为Key 去取map里面的值的话能取,到恰恰就证明了这种猜想。所以解以解办法就是让我们自己定义key生效:

在这里插入图片描述

解决办法:使用@Param 注解:

# 就是在mapper接口中参数列表中参数前面加上:@Param("mapper中#括号中的字段名")来进行关联映射,之后可以通过这个值去取到相应的参数值。

在这里插入图片描述

(3)、当参数为Map类型时:

1.定义mapper接口:

 Employee selectMap(Map<String,Object> map);

2.在mapper.xml文件编写Sql语句:

<select id="selectMap" resultType="cn.js.domain.Employee">
        select * from employee where id=#{id} and name=#{name}
</select>

在这里插入图片描述

3.测试:

		  /**
            *
            * @description: 通过Map集合传递参数
            * @param:
            * @retuen:
            **/
         @Test
         public void test03(){
    
    
             Map<String,Object> map =new HashMap<>();
             map.put("id",4L);
             map.put("name","步惊云");
             Employee employee = mybatisTestMapper.selectMap(map);
             System.out.println("---+++: " + employee);


         }

在这里插入图片描述

(4)、当参数类型为对象的时候:

# 从对象中获取值其实就是写对象中的字段名称,mybotis会将你给定的名称前面加上get,再将你给定的名称首字母大写,去调用你传递进来的对象从而获取到对象的字段值

# useGeneratedKeys: 
      此属性用于打开自动返回主键信息,主键会自动返回到传递进来的对象当中
# keyProperty: 
  	  此属性用于告诉mybatis,主键值返回给传递进来的对象的那个字段
# keuCoLumn:
      此属性用于告mybatis,对于操作的这张求那一列是主,又因为通常主键列就是第一列,所以默认可以不写此属件,因为默认mybatis读取的就是第一列

1.定义新增mapper接口:

Long inserct(Employee employee);

2.在mapper.xml文件编写Sql语句:

<insert id="inserct"
            parameterType="cn.js.domain.Employee"
            useGeneratedKeys="true"
            keyProperty="id"
            keyColumn="id">

        insert  into employee(name,pid,sex) values (#{name},#{pid},{sex})
</insert>

3.测试:

			/**
            *
            * @description: 通过对象传递参数,新增一条参数
            * @param:
            * @retuen:
            **/
         @Test
         public void test04(){
    
    
             Employee employee=new Employee();
             employee.setName("张三丰");
             employee.setPid(5L);
             employee.setSex("男");
             Long inserct = mybatisTestMapper.inserct(employee);
             Long id = employee.getId();
             System.out.println("返回的ID为:"+id);


         }

在这里插入图片描述

二、设置Mapper.xml 文件模板:

<?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">

<mapper namespace="xx.xx.xxMapper">

</mapper>

在这里插入图片描述

在这里插入图片描述

三、结果集封装:

1、一条结果集封装:

1.1、对象封装结果:

-- 当查询结果为一条时,使用对象封装,结果为多条时,一定不能使用对象,否则报错
1.定义mapper接口:
Employee selectAone(Long id);
2.在mapper.xml文件编写Sql语句:
<select id="selectAone" resultType="cn.js.domain.Employee">
        select * from employee where id=#{id}
</select>
3.测试:
		 @Test
        public void test01(){
    
    
            Employee employee = mybatisTestMapper.selectAone(1L);
            System.out.println(employee);
        }

在这里插入图片描述

1.2、List 封装结果:

1.定义mapper接口:
List<Employee> selectList(String id);
2.在mapper.xml文件编写Sql语句:
 <select id="selectList" resultType="cn.js.domain.Employee">
        select * from employee where id=#{id}
    </select>
3.测试:
		@Test
         public void test05(){
    
    
             List<Employee> employees = mybatisTestMapper.selectList(2L);
             for (Employee employee : employees) {
    
    
                 System.out.println(employee);
             }
         }

在这里插入图片描述

1.3、Map封装结果:

1.定义mapper接口:
Map<String,Object> selectByMap(String name);
2.在mapper.xml文件编写Sql语句:
<select id="selectByMap" resultType="java.util.Map">
        select * from employee where name=#{name}
</select>
3.测试:
		@Test
         public void test06(){
    
    
             Map<String, Object> map = mybatisTestMapper.selectByMap("张三丰");
             System.out.println("map封装数据:"+ map);
         }

在这里插入图片描述

1.4、使用 @MapKey注解封装结果

通过 @MapKey注解指定一个表中字段的值作为Map中的Key进行数据结果的封装
1.定义mapper接口:
    @MapKey("name")
    Map<String,Object> selectByMapkey(String name);
2.在mapper.xml文件编写Sql语句:
    <select id="selectByMapkey" resultType="java.util.Map">
        select * from employee where name=#{name}
    </select>
3.测试:
@Test
public void test07(){
    
    
    Map<String, Object> map = mybatisTestMapper.selectByMapkey("聂风");
    System.out.println(map);
}

在这里插入图片描述

2、多条数据封装:

2.1、List 封装结果:

1.定义mapper接口:
 List<Employee> selectList();
2.在mapper.xml文件编写Sql语句:
<select id="selectList" resultType="cn.js.domain.Employee">
        select * from employee
</select>
3.测试:
@Test
 public void test05(){
    
    
     List<Employee> employees = mybatisTestMapper.selectList();
     for (Employee employee : employees) {
    
    
          System.out.println(employee);
    }
 }

在这里插入图片描述

2.2、Map封装结果:

1.定义mapper接口:
List<Map<String,Object>> selectLsistMap();
2.在mapper.xml文件编写Sql语句:
<select id="selectLsistMap" resultType="java.util.Map">
        select * from employee
</select>
3.测试:
 @Test
         public void test09(){
    
    
             List<Map<String, Object>> maps = mybatisTestMapper.selectLsistMap();
             for (Map<String, Object> map : maps) {
    
    
                 System.out.println(map);
             }
         }

在这里插入图片描述

四、Mybatis动态表名:

(1).在实际开发中,一张表的数据过多时,会影响操作性能,此时就会使用水平切分,将一张表的数据,切分到多张表共同存储一张表的数据
(2).当数据在多张表时,我们查询数据表名就不固定了,那么就需要将表名通过参数的形式传递到5QL中,此时我们可以使用$0的方式获取参数作为表名
# 注意此时不能使用#{},因为#{}会帮助我们添加单引号,表名是不能添加单引号的,所有选择${};

在这里插入图片描述

五、MyBatis解决字段映射名称不一致方案:

在实际开发中,数据库中的字段名规范是以下划线分隔,而java的实体类字段规范是小蛇峰,所以这就会导致字段自动映射失败,无法将数据库数据封装到实体类对象中

在这里插入图片描述

解决办法:

1.取别名:

1.定义mapper接口:
Employee selectnameo(String name);
2.在mapper.xml文件编写Sql语句:
 <select id="selectnameo" resultType="cn.js.domain.Employee">
        select  id ,name,pid,sex,dept_name deptName from employee where name=#{name}
    </select>

在这里插入图片描述

3.测试:
		@Test
         public void test10(){
             Employee employee = mybatisTestMapper.selectnameo("雄霸");
             System.out.println("起别名:"+employee);
         }

在这里插入图片描述

2、开启开启驼峰字段转换:

在配置文件中开启
	 map-underscore-to-camel-case: true #开启驼峰字段转换
1.定义mapper接口:
Employee selectnameo(String name);
2.在mapper.xml文件编写Sql语句:
 <select id="selectnameo" resultType="cn.js.domain.Employee">
        select  id ,name,pid,sex,dept_name  from employee where name=#{name}
</select>
3.测试:
		@Test
         public void test10(){
    
    
             Employee employee = mybatisTestMapper.selectnameo("雄霸");
             System.out.println("起别名:"+employee);
         }

在这里插入图片描述

3、手动映射 ( 重点 ):

resultMop: 
	自定义映射,标识返回值类型,只不过映射关系需要我们自己定义,如果使用自定义映射,即便名称一致也必须做映别,否则不会返回该字段;即所有查询出来的字段都得做映射,否则的话不会返回该字段数据。

resultMap: 此标签专门用来定义自定义映射的
type: 告诉ybatis把自定义映射封我到那个对象中

映射标签:
	    id: 专门用来映射主键的
	result: 此标就是专门用来映射除了主键的其他字段的

属性:
	property: 指定实体美中的那个宁段做映射
	  column: 指定表中一列映射
1.定义mapper接口:
List<Employee> selectResutMap();
2.在mapper.xml文件编写Sql语句:
 <resultMap id="selectResutMa" type="cn.js.domain.Employee">
        <id property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="pid" column="pid"/>
        <result property="sex" column="sex"/>
        <result property="detName" column="dept_name"/>
    </resultMap>

    <select id="selectResutMap" resultMap="selectResutMa">
        select * from employee
    </select>

在这里插入图片描述

3.测试:
 		@Test
         public void test11(){
    
    
             List<Employee> employees = mybatisTestMapper.selectResutMap();
             for (Employee employee : employees) {
    
    
                 System.out.println(employee);
             }
         }

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_45525848/article/details/129910936