首页 > 其他分享 >封装MyBatis输出结果-简单类型,对象类型,map,resulemap,模糊查询

封装MyBatis输出结果-简单类型,对象类型,map,resulemap,模糊查询

时间:2022-11-07 13:24:37浏览次数:48  
标签:map name public student MyBatis resulemap id select String

封装 MyBatis 输出结果

resultType: 执行 sql 得到 ResultSet 转换的类型,使用类型的完全限定名或别名。 注意如果返回的是集合,那应该设置为集合包含的类型,而不是集合本身。resultType 和 resultMap,不能同时使用。

1.对象类型

实体类中不仅表对应的实体类可以拿到数据库中的值,只要字段名字对应还可以赋值给其他类、

  1. 定义一个类

    package com.bjpowernode.vo;
    
    public class ViewStudent {
    
        private Integer id;
        private String name;
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        @Override
        public String toString() {
            return "ViewStudent{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    '}';
        }
    }
    
    
  2. 配置mappery映射,将数据库中的数据赋值给这个viewstudent

        <!--selectStudentReturnViewStudent-->
        <select id="selectStudentReturnViewStudent" resultType="ViewStudent">
            select id,name  from student where id=#{sid}
        </select>
    
  3. 测试如下:

在接口的对应配置文件中:

    <select id="selectStudentById"  resultType="Student">
        select id,name, email,age from student where id=#{studentId}
    </select>

执行结果如下:

2. 简单类型

接口方法:
int countStudent();
mapper 文件:
<select id="countStudent" resultType="int">
 select count(*) from student
</select>
    
测试方法:
@Test
public void testRetunInt(){
 int count = studentDao.countStudent();
 System.out.println("学生总人数:"+ count);
}

结果如下:

3. map

sql 的查询结果作为 Map 的 key 和 value。推荐使用 Map<Object,Object>。注意:Map 作为接口返回值,sql 语句的查询结果最多只能有一条记录。大于一条记录是错误。

接口方法:

    //定义方法返回Map
    Map<Object,Object> selectMapById(Integer id);

mapper 映射文件

只能最多返回一行记录。多余一行是错误

    <!--返回Map
        1)列名是map的key, 列值是map的value
        2)只能最多返回一行记录。多余一行是错误
    -->
    <select id="selectMapById" resultType="java.util.HashMap">
        select id,name,email from student where id=#{stuid}
    </select>

测试方法如下:

    //返回Map
    @Test
    public void testSelecMap(){

        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        StudentDao dao  =  sqlSession.getMapper(StudentDao.class);

        Map<Object,Object> map = dao.selectMapById(1001);
        System.out.println("map=="+map);
    }

结果如下;

4. resultMap

resultMap 可以自定义 sql 的结果和 java 对象属性的映射关系。更灵活的把列值赋值给指定属性。常用在列名和 java 对象属性名不一样的情况。

其实就是手动的让数据库中的列值赋值到实体类中的各个属性上,具体实现如下:

    <!--使用resultMap
        1)先定义resultMap
        2)在select标签,使用resultMap来引用1定义的。
    -->

    <!--定义resultMap
        id:自定义名称,表示你定义的这个resultMap
        type:java类型的全限定名称
    -->
    <resultMap id="studentMap" type="com.bjpowernode.domain.Student">
        <!--列名和java属性的关系-->
        <!--注解列,使用id标签
            column :列名
            property:java类型的属性名
        -->
        <id column="id" property="id" />
        <!--非主键列,使用result-->
        <result column="name" property="name" />
        <result column="email" property="email" />
        <result column="age" property="age" />

    </resultMap>
    <select id="selectAllStudents" resultMap="studentMap">
        select id,name, email , age from student
    </select>

5. 实体类属性名和列名不同的处理方式可能会用到

  1. 方法一:使用resultMap

    • 创建实体类

      package com.bjpowernode.domain;
      
      public class MyStudent {
      
          private Integer stuid;
          private String stuname;
          private String stuemail;
          private Integer stuage;
      
          public Integer getStuid() {
              return stuid;
          }
      
          public void setStuid(Integer stuid) {
              this.stuid = stuid;
          }
      
          public String getStuname() {
              return stuname;
          }
      
          public void setStuname(String stuname) {
              this.stuname = stuname;
          }
      
          public String getStuemail() {
              return stuemail;
          }
      
          public void setStuemail(String stuemail) {
              this.stuemail = stuemail;
          }
      
          public Integer getStuage() {
              return stuage;
          }
      
          public void setStuage(Integer stuage) {
              this.stuage = stuage;
          }
      
          @Override
          public String toString() {
              return "MyStudent{" +
                      "stuid=" + stuid +
                      ", stuname='" + stuname + '\'' +
                      ", stuemail='" + stuemail + '\'' +
                      ", stuage=" + stuage +
                      '}';
          }
      }
      
      
    • 配置mapper文件

      <resultMap id="myStudentMap" type="com.bjpowernode.domain.MyStudent">
              <!--列名和java属性的关系-->
      
              <id column="id" property="stuid" />
              <!--非主键列,使用result-->
              <result column="name" property="stuname" />
              <result column="email" property="stuemail" />
              <result column="age" property="stuage" />
      
          </resultMap>
          <!--列名和属性名不一样:第一种方式-->
          <select id="selectMyStudent" resultMap="myStudentMap">
      
               select id,name, email , age from student
          </select>
      
      
    • 测试如下:

  2. 方式二:直接在sql中该表列名字(更简单写)

        <!--列名和属性名不一样:第二种方式
           resultType的默认原则是 同名的列值赋值给同名的属性, 使用列别名(java对象的属性名)
        -->
        <select id="selectDiffColProperty" resultType="com.bjpowernode.domain.MyStudent">
            select id as stuid ,name as stuname, email as stuemail , age stuage from student
        </select>
    

    6. 模糊 like

    模糊查询的实现有两种方式, 一是 java 代码中给查询数据加上“%” ; 二是在 mapper 文件 sql 语句的条件位置加上“%”

    需求:查询姓名有“力”的

例 1: java 代码中提供要查询的 “%力%”
接口方法:
List<Student> selectLikeFirst(String name);
mapper 文件:
<select id="selectLikeFirst" resultType="com.bjpowernode.domain.Student">
 select id,name,email,age from student
 where name like #{studentName}
</select>
测试方法:
@Test
public void testSelectLikeOne(){
 String name="%力%";
 List<Student> stuList = studentDao.selectLikeFirst(name);
 stuList.forEach( stu -> System.out.println(stu));
}
例 2:mapper 文件中使用 like name "%" #{xxx} "%"
接口方法:
List<Student> selectLikeSecond(String name);
mapper 文件:
<select id="selectLikeSecond" resultType="com.bjpowernode.domain.Student">
 select id,name,email,age from student
 where name like "%" #{studentName} "%"
</select>
测试方法:
@Test
public void testSelectLikeSecond(){
 String name="力";
 List<Student> stuList = studentDao.selectLikeSecond(name);
 stuList.forEach( stu -> System.out.println(stu));
}
    <!--第一种 like , java代码指定 like的内容-->
    <select id="selectLikeOne" resultType="com.bjpowernode.domain.Student">
        select id,name,email,age from student where name like #{name}
    </select>

    <!--第二种方式:在mapper文件中拼接 like的内容-->
    <select id="selectLikeTwo" resultType="com.bjpowernode.domain.Student">
        select id,name,email,age from student where name  like "%" #{name} "%"
    </select>

标签:map,name,public,student,MyBatis,resulemap,id,select,String
From: https://www.cnblogs.com/atao-BigData/p/16865597.html

相关文章

  • Mybatis下的SQL注入
    Mybatis概述mybatis是一个优秀的基于java的持久层框架,它内部封装了jdbc,使开发者只需要关注sql语句本身,而不需要花费精力去处理加载驱动、创建连接、创建statement......
  • hashtable和hashmap的区别
    1、两者继承的类不同hashtable继承dictionary类,hashmap继承abstractHashMap类,2、两者提供的接口不同3、两者对null处理不同hashmap中key不能为null,但是value可以为null......
  • Transactional mybatis plus 不生效
    @Transactional默认是当方法抛出RuntimeException才会回滚,可以使用@Transactional(rollbackFor=Exception.class)指定具体异常时就回滚代码:@Transactional(rollbac......
  • HashMap 的 7 种遍历方式与性能分析!
    参考来自于:HashMap的7种遍历方式与性能分析!方法之1:使用forEachpublicclassHashMapTest{publicstaticvoidmain(String[]args){//创建并赋值......
  • MyBatis-Plus
    1.代码生成主要依赖<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.2.0</version></de......
  • 第三章:MyBatis框架Dao代理-动态代理简化代码
    第三章:MyBatis框架Dao代理内容列表◼Dao接口动态代理◼参数传递◼处理查询结果◼like和主键1Dao代理实现CURD1.1去掉Dao接口的实现类1.2getMapper......
  • MyBatisPlus快速入门
    MyBatisPlus快速入门需要的基础:MyBatisSpringSpringMVC是什么?MyBatis本来就是简化JDBC操作的!官网:https://mp.baomidou.com/MyBatisPlus,简化MyBatis......
  • 并发工具之 Semaphore & CountDownLatch
    1.semaphore是什么?Semaphore字面意思是信号量的意思。它的作用是控制访问特定资源的线程数量,底层依赖AQS的状态state,是生产中比较常用的一个工具类。(基于共享模式)//......
  • mall学习教程笔记--Mybatis generator和Swagger
    github学习项目--mall学习教程https://www.macrozheng.com/mall/catalog/mall_catalog.htmlMybatisgenerator配置文件介绍MyBatis的代码生成器,可以根据数据库生成mode......
  • ObjectMapper详细介绍
    参考声明:https://blog.csdn.net/qq_42017395/article/details/107555339简介ObjectMapper类(com.fasterxml.jackson.databind.ObjectMapper)是Jackson的主要类,它可以......