• 【JavaEE】MyBatis


    1.MyBatis介绍

    1.什么是MyBatis?

    • MyBatis是一款优秀的 持久层框架用于简化JDBC开发
    • MyBatis本是 Apache 的一个开源项目 iBatis,2010年这个项目由 apache software foundation 迁移到了 google code,并且改名为 MyBatis。2013年11月迁移到 Github
      官网:https://mybatis.org/mybatis-3/zh/index.html
       

    2.持久层

    • 负责将数据到保存到 数据库 的那一层代码
    • JavaEE三层架构:表现层、业务层、持久层
       

    3.框架

    • 框架就是一个半成品软件,是一套可重用的、通用的、软件基础代码模型
    • 在框架的基础之上构建软件编写更加高效、规范、通用、可扩展

    在这里插入图片描述
    在这里插入图片描述

     

    2.MyBatis快速入门

    查询 user 表中所有数据

    在这里插入图片描述

    1、添加依赖:
    在这里插入图片描述
    2、编写mybatis-config.xml配置文件
    在这里插入图片描述
    3.编写sql语句映射文件(UserMapper.xml)
    在这里插入图片描述
    4.获取工厂构造的对象,执行sql语句
    在这里插入图片描述

     

    3.Mapper代理开发

    在这里插入图片描述
     在这里插入图片描述

    1.定义接口,返回值类型、方法名对应映射文件
    在这里插入图片描述
    2.maper映射文件放置相同目录下,名称空间为接口全限定名
    在这里插入图片描述
    3.mapper代理方式mybatis-config.xml可以使用包扫描的方式加载映射文件
    在这里插入图片描述
    4.获取 Mapper 接口对象,调用相应方法执行sql语句
    在这里插入图片描述

     

    4.MyBatis核心配置文件

    配置的属性应符合以下顺序(官网),否则报错
    在这里插入图片描述

    
    DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "https://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
    
        
        <typeAliases>
            <package name="com.eve.pojo"/>
        typeAliases>
    
        
        <environments default="development">
            <environment id="development">
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                    
                    <property name="driver" value="com.mysql.jdbc.Driver"/>
                    <property name="url" value="jdbc:mysql:///mybatis?useSSL=false"/>
                    <property name="username" value="root"/>
                    <property name="password" value="abc123"/>
                dataSource>
            environment>
            <environment id="test">
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                    
                    <property name="driver" value="com.mysql.jdbc.Driver"/>
                    <property name="url" value="jdbc:mysql:///testdb?useSSL=false"/>
                    <property name="username" value="root"/>
                    <property name="password" value="abc123"/>
                dataSource>
            environment>
        environments>
        <mappers>
            
            
            
            <package name="com.eve.mapper"/> 
        mappers>
    configuration>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43

     

    5.配置文件完成增删改查

    MyBatis动态Sql:
    在这里插入图片描述

    MyBatisX插件:
    在这里插入图片描述

    在这里插入图片描述

     

    5.1 查询

    1、表列和与属性名不一样(resultMap标签)、特殊字符处理(转义字符、CDATA区)

    
    DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.eve.mapper.BrandMapper">
    
        
    
        <resultMap id="brandResultMap" type="com.eve.pojo.Brand">
            
            <result column="brand_name" property="brandName"/>
            <result column="company_name" property="companyName"/>
        resultMap>
    
        <select id="selectAll" resultMap="brandResultMap">
            select *
            from tb_brand;
        select>
    
        <select id="selectById" resultMap="brandResultMap">
            select *
            from tb_brand where id = #{id};
        select>
    
        <select id="selectById1" resultMap="brandResultMap">
            select *
            from tb_brand where id
            
            #{id};
        select>
    
    mapper>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49

     
    2、多参数传递(多个参数、对象、集合)

    在这里插入图片描述

    public class BrandMapperTest {
    
        @Test
        public void selectByCondition() throws IOException {
            // 接收参数
            int status = 1;
            String companyName = "华为";
            String brandName = "华为";
    
            // 处理参数
            companyName = "%" + companyName + "%";
            brandName = "%" + brandName + "%";
    
            // 封装对象
    //        Brand brand = new Brand();
    //        brand.setStatus(status);
    //        brand.setCompanyName(companyName);
    //        brand.setBrandName(brandName);
    
            Map map = new HashMap();
            map.put("status",status);
            map.put("companyName",companyName);
            map.put("brandName",brandName);
    
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            SqlSession sqlSession = sqlSessionFactory.openSession();
            BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
    
            List<Brand> brands = mapper.selectByCondition(map);
            System.out.println(brands);
    
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

     
    2、动态条件查询

    在这里插入图片描述
     
    多条件动态查询:
    在这里插入图片描述
     
    单条件查询:
    在这里插入图片描述
    在这里插入图片描述

     

    5.2 添加/修改

    添加:在这里插入图片描述
     
    返回主键(两个属性)

    在这里插入图片描述
     
    修改:
    在这里插入图片描述
     
    动态修改(set标签)
    在这里插入图片描述

     

    5.3 删除

    在这里插入图片描述
     
    批量删除(foreach标签)
    在这里插入图片描述

     

    6.MyBatis参数传递

    在这里插入图片描述
     
    封装:

    在这里插入图片描述

     
    MyBatis封装参数方法源码:

    public Object getNamedParams(Object[] args) {
          int paramCount = this.names.size();
           if (args != null && paramCount != 0) {
               if (!this.hasParamAnnotation && paramCount == 1) {
                   Object value = args[(Integer)this.names.firstKey()];
                   return wrapToMapIfCollection(value, this.useActualParamName ? (String)this.names.get(0) : null);
               } else {
                   Map<String, Object> param = new MapperMethod.ParamMap();
                   int i = 0;
    
                   for(Iterator var5 = this.names.entrySet().iterator(); var5.hasNext(); ++i) {
                       Map.Entry<Integer, String> entry = (Map.Entry)var5.next();
                       param.put(entry.getValue(), args[(Integer)entry.getKey()]);
                       String genericParamName = "param" + (i + 1);
                       if (!this.names.containsValue(genericParamName)) {
                           param.put(genericParamName, args[(Integer)entry.getKey()]);
                       }
                   }
    
                   return param;
               }
           } else {
               return null;
           }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

     
    &、map传递时,如何取出里面的User对象里的username、password值
    在这里插入图片描述

    <select id="selectBrandByName" resultMap="brandResultMap">
          select *
          from tb_brand
          where brand_name = #{brand.brandName}
          and company_name = #{brand.companyName};
    select>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

     

    7.注解完成增删改查

    在这里插入图片描述

    使用注解来映射简单语句会使代码显得更加简洁,但对于稍微复杂一点的语句,Java注解不仅力不从心,还会让你本就复杂的SQL语句更加混乱不堪。因此,如果你需要做一些很复杂的操作,最好用XML来映射语句。
     
    选择何种方式来配置映射,以及认为是否应该要统一映射语句定义的形式,完全取决于你和你的团队。换句话说,永远不要拘泥于一种方式,你可以很轻松的在基于注解和ML的语句映射方式间自由移植和切换。

  • 相关阅读:
    IDEA创建SparkSQL程序_大数据培训
    Hive概述
    初阶数据结构 二叉树常用函数 (二)
    基于or-tools的护士排班问题建模求解
    FlinkSQL CDC实现同步oracle数据到mysql
    聊天机器人的实践过程
    机器学习:在线学习和离线学习区别
    我们用python来写一个节点间消息收发的demo
    python写一个文本处理器
    H5实现预览pdf(PC+移动端都可以)
  • 原文地址:https://blog.csdn.net/T_158327/article/details/128062583