Mybatis笔记(全)

Mybatis

简介

根据狂神说的mybatis教学编程

https://www.bilibili.com/video/BV1NE411Q7Nx?p=1

1.1 、什么是Mybatis

MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。(主要简化了连接数据库的代码)

持久层,理解为数据保存在数据库或者硬盘一类可以保存很长时间的设备里面,即数据存放在持久层设备上

<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>3.5.4</version>
</dependency>

1.2 、持久化

数据持久化

持久化就是将程序的数据在持久状态和瞬时状态转化的过程

内存断电及失

1.3 、持久层

DAO层,service层,Controller

完成持久化工作的代码块

层界限明显

1.4 、为什么需要Mybatis

传统的JDBC代码太复杂、简化、框架、自动化

方便

将数据存入到数据库中

第一个Mybatis程序

思路:搭建环境——>导入Mybatis——>编写代码——>测试

2.1 、搭建环境

SQLyog

CREATE DATABASE  `mybatis`;
  USE  `mybatis`
  CREATE  TABLE `user`(
  `id` INT(20) NOT NULL   PRIMARY KEY,
  `name`  VARCHAR(30) DEFAULT NULL,
  `password`  VARCHAR(20)  DEFAULT NULL

   )ENGINE=INNODB DEFAULT  CHARSET=utf8;
   INSERT  INTO `user` (`id`,`name`,`password`) VALUES 
 (1,'德莱文','123'),
 (2,'李青','1234'),
 (3,'金克丝','12345')

IDEA

新建项目:

  1. 新建一个普通的maven项目
  2. 删除src目录
  3. 导入maven依赖,驱动配置
<!--导入依赖-->
    <dependencies>
<!--        mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.49</version>
        </dependency>
<!--        Mybatis驱动-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.4</version>
        </dependency>
<!--        Junit驱动-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

2.2、 创建一个模块

  • 编写Mybatis的核心配置文件

  • mybatis-config.xml 配置文件

    <?xml version="1.0" encoding="UTF8" ?>
    <!DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <!--核心配置文件-->
    <!--JDBC数据库连接-->
    <configuration>
        <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://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                    <property name="username" value="root"/>
                    <property name="pwd" value="root"/>//这里是数据库的密码
                </dataSource>
            </environment>
        </environments>
    <!--每一个Mapper.xml都需要在Mybatis核心配置文件中注册-->
        <mappers>
            <mapper resource="com/ma/dao/UserMapper.xml" />
        </mappers>
    </configuration>
    
  • 编写工具类

    
    //工具类  获取SQLSessionFactory
    public class MybatisUtils {
        private  static  SqlSessionFactory sqlSessionFactory;
        static {
            try {
            String resource = "Mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            } catch (IOException e) {
            e.printStackTrace();
            }
        }
    // 我们可以从中获得 SqlSession 的实例。SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
    // 你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句
       public  static SqlSession getSqlSession(){
          return sqlSessionFactory.openSession();
    
       }
    }
    

2.3、编写代码

  • 实体类

    public class User {
        private  int id;
        private  String  name;
        private String  password;
    
        public User() {
        }
    
        public User(int id, String name, String password) {
            this.id = id;
            this.name = name;
            this.password = password;
        }
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", password='" + password + '\'' +
                    '}';
        }
    }
    
  • DAO接口类

    import com.ma.pojo.User;
    
    import java.util.List;
    
    public interface UserDao {
        List<User> getUserList();
    }
    
  • 接口实现类

<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace=绑定一个对应的DAO接口-->
<mapper namespace="com.ma.dao.UserDao">
   <select id="getUserList" resultType="com.ma.pojo.User">
   select * from mybatis.user
   </select>
</mapper>

2.4、测试

Junit测试

public class UserDaoTest {
    @Test
//    第一步获取sqlSession对象
    public  void  test(){
         SqlSession sqlSession = MybatisUtils.getSqlSession();
//        执行Sql   方法一:getMapper
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        List<User> userList = mapper.getUserList();
        for (User user:userList){
            System.out.println(user);
        }
        sqlSession.close();
    }

}

遇到的问题

  1. 配置文件没有注册
  2. 绑定接 口错误
  3. 方法名不对
  4. 返回类型不对
  5. Maven导出资源错误
  6. UTF-8 改为UTF8

3.CRUD

3.1、namespace

namespace中的包名和Dao/mapper的接口的包名一致

3.2 、select

选择,查询语句:

  • id:就是对应的namespace中的方法名
  • resultType:sql语句执行的返回值
  • parameterType:返回参数类型

1.写接口

  List<User> getUserList();xxxxxxxxxx //    添  List<User> getUserList();    int addUser(User user);

2.写UserMapper

<select id="getUserList" resultType="com.ma.pojo.User">
select * from mybatis.user
</select>

3.写Test

    @Test
//    第一步获取sqlSession对象
    public void test() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
//        执行Sql   方法一:getMapper
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        List<User> userList = mapper.getUserList();
        for (User user : userList) {
            System.out.println(user);
        }
        sqlSession.close();
    }

3.3、Insert

   <insert id="addUser"  parameterType="com.ma.pojo.User">
insert  into mybatis.user(id,name,password) values(#{id},#{name},#{password});
   </insert>

3.4、update

   <update id="updateUser" parameterType="com.ma.pojo.User">
      update mybatis.user set name=#{name},password=#{password}  where id=#{id} ;
   </update>

3.5 、delete

   <delete id="deleteUser" parameterType="int">
      delete from  mybatis.user  where id=#{id};
   </delete>

3.6、万能Map

实体类,字段或参数过多,考虑使用Map

//    万能的map
    int addUser2(Map<String,Object> map);
<!--   对象的属性,直接提取出来-->
   <insert id="addUser2"  parameterType="map">
insert  into mybatis.user(id,name,password) values(#{id},#{name},#{password});
   </insert>
   @Test
    public void test4() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id",4);
        map.put("name","卡莎");
        map.put("password","66666");
        mapper.addUser2(map);
//        提交事务
        sqlSession.commit();
        sqlSession.close();
    }

Map传递参数,直接在sql中取出key parameterType=“map”

对象传递参数,直接在SQL中其对象的属性即可 parameterType=“object”

只有一个基本类型参数的情况下,直接在SQL中取出

多个参数使用map或者注解

模糊查询

java代码执行的时候传递通配符 % %

List<User> userlist =mapper.getUserLike("%李%");

在SQL拼接中固定死的通配符,防止出现字节错误

select * from user where name like "%"#{value}"%"

4、配置解析

1、核心配置文件

  • mybatis-config.xml

  • Mybatis的配置文件包括了深深影响Mybatis行为的设置和属性信息

    configuration(配置)
     properties(属性)
    settings(设置)
    typeAliases(类型别名)
    typeHandlers(类型处理器)
    objectFactory(对象工厂)
    plugins(插件)
    environments(环境配置)
    	environment(环境变量)
    	transactionManager(事务管理器)
    	DataSource(数据源)
    databaseldProvider(数据厂商标识)
    mappers(映射器)
    

2、环境配置(environments)

MyBatis 可以配置成适应多种环境,这种机制有助于将 SQL 映射应用于多种数据库之中, 现实情况下有多种理由需要这么做。

尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。

在 MyBatis 中有两种类型的事务管理器(也就是 type=“[JDBC|MANAGED]”):

  • JDBC – 这个配置直接使用了 JDBC 的提交和回滚设施,它依赖从数据源获得的连接来管理事务作用域。
  • MANAGED – 这个配置几乎没做什么。它从不提交或回滚一个连接,而是让容器来管理事务的整个生命周期(比如 JEE 应用服务器的上下文)。 默认情况下它会关闭连接。然而一些容器并不希望连接被关闭,因此需要将 closeConnection 属性设置为 false 来阻止默认的关闭行为。

POOLED– 这种数据源的实现利用“池”的概念将 JDBC 连接对象组织起来,避免了创建新的连接实例时所必需的初始化和认证时间。 这种处理方式很流行,能使并发 Web 应用快速响应请求。

3、属性(properties)

通过properties属性来实现引用配置文件

这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。

请添加图片描述

配置文件:db.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8
username=root
password=root

然后根据 properties 元素中的 resource 属性读取类路径下属性文件,或根据 url 属性指定的路径读取属性文件,并覆盖之前读取过的同名属性。

 <properties resource="db.properties">
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </properties>
  • 可以直接引入外部文件
  • 可以在其中增加一些属性配置
  • 如果两个文件有同一个字段 ,优先使用外部配置

4、类型别名(typeAliases)

类型别名可为 Java 类型设置一个缩写名字。 它仅用于 XML 配置,意在降低冗余的全限定类名书写。

<typeAliases>
    <typeAlias type="com.xiao.pojo.User" alias="User"/>
</typeAliases>

也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean

扫描实体类的包,它的默认别名就是为这个类的类名,首字母小写

<typeAliases>
   <package name="com.xiao.pojo"/>
</typeAliases>

在实体类比较少的时候,使用第一种方法

在实体类比较多的时候,使用第二种方法

若有注解,则别名为其注解值。见下面的例子:

@Alias("author")
public class 实体类 {
    ...
}

5、设置

这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为。 下表描述了设置中各项设置的含义、默认值等。

请添加图片描述

请添加图片描述

6、映射器

MapperRegistry:注册绑定我们的Mapper文件;

在配置文件中写到,在核心文件需要注册

方法一:xml文件绑定

<!--每一个Mapper.xml都需要在Mybatis核心配置文件中注册-->
<!--    映射器-->
<mappers>
    <mapper resource="com/xiao/Dao/UserMapper.xml" />
</mappers>

方法二 :使用class文件绑定

<mappers>
<mapper class="com.xiao.Dao.UserMapper"/>
<mappers>

注意点:

  • 接口和它的Mapper配置文件必须同名
  • 接口和它的Mapper配置文件必须在同一个包下

方法三:扫描包

  <mappers>
<!--        <mapper resource="com/xiao/Dao/UserMapper.xml" />-->
   <package name="com.xiao.Dao"/>
    </mappers>

注意点:

  • 接口和它的Mapper配置文件必须同名
  • 接口和它的Mapper配置文件必须在同一个包下

7、生命周期

不同作用域和生命周期类别是至关重要的,因为错误的使用会导致非常严重的并发问题

请添加图片描述

SqlSessionFactoryBuilder

  • 一旦创建了 SqlSessionFactory,就不再需要它
  • 局部变量

SqlSessionFactory

  • 理解为“数据库连接池”
  • 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例。
  • SqlSessionFactory 的最佳作用域是应用作用域
  • 最简单就是使用单例模式或者静态单例模式

SQLSession:

  • my连接到连接池的一个请求

  • 用完之后关闭,资源占有

  • SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域

    SQL Mapper是SQL的映射,需要连接到连接池
    请添加图片描述

5、解决属性名和字段名不一致

1、 问题

public class User {
    private  int id;
    private  String  name;
    private String  pwd;

请添加图片描述

<select id="getUserById" parameterType="int" resultType="com.xiao.pojo.User">
   select id,name,password   from mybatis.user where id=#{id}
    //select id,name,password as  pwd  from mybatis.user where id=#{id}   
</select>

解决方法:

  • 起别名 password as pwd

    select id,name,password as pwd from mybatis.user where id=#{id}

2、resultMap

结果集映射

   <resultMap id="UserMap" type="User">
<!--column数据库中的字段  property实体类中的属性  -->
      <result column="id" property="id"></result>
      <result column="name" property="name"></result>
      <result column="password" property="pwd"></result>
   </resultMap>
   <select id="getUserById" parameterType="int" resultMap="UserMap">
      select *  from mybatis.user where id=#{id}
   </select>

resultMap 元素是 MyBatis 中最重要最强大的元素

ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。

之前你已经见过简单映射语句的示例,它们没有显式指定 resultMap

ResultMap 的优秀之处——你完全可以不用显式地配置它们

6、日志

6.1 、日志工厂

数据库操作出现异常,需要日志

logImpl指定 MyBatis 所用日志的具体实现,未指定时将自动查找。SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING
  • SLF4J
  • LOG4J ***
  • LOG4J2
  • JDK_LOGGING
  • COMMONS_LOGGING
  • STDOUT_LOGGING 掌握
  • NO_LOGGING

在Mybatis中具体使用哪个-设置设定

STDOUT_LOGGING 标准日志输出

请添加图片描述

<settings>
    <setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>

6.2、 Log4j

Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件

我们也可以控制每一条日志的输出格式;通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程。最令人感兴趣的就是,这些可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。

1、导入log4j的包

<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

2、log4j.properties

#将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码
log4j.rootLogger=DEBUG,console,file

#控制台输出的相关设置
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%m%n

#文件输出的相关设置
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/xiao.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][p%d{yy-MM-dd}][%c]%m%n

#日志输出级别
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

3、配置log4j为日志的实现

<settings>
    <setting name="logImpl" value="LOG4J"/>
</settings>

4、log4j使用,测试运行

简单使用

  1. 在使用log4j的类中,导入import org.apache.log4j.Logger;

  2. 日志对象,参数为当前类的class

    static Logger logger = Logger.getLogger(UserDaoTest.class);
    

7、分页

减少数据的处理量

使用limit分页

SELECT * FROM USER LIMIT startIndex,pageSize;

使用mybatis实现分页,核心SQL

请添加图片描述

  1. 接口

    List<User>  getUserByLimit(Map<String,Integer> map );
    
  2. Mapper.xml

     <resultMap id="Map" type="User">
          <result column="id" property="id"></result>
          <result column="name" property="name"></result>
          <result column="password" property="pwd"></result>
       </resultMap>
    <select id="getUserByLimit" parameterType="map"  resultMap="Map">
        select  * from mybatis.user  limit  #{startIndex},#{pageSize}
    </select>
    
  3. 测试

@Test
public void  getUserByLimit(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    HashMap<String, Integer> map = new HashMap<String, Integer>();
    map.put("startIndex",0);
    map.put("pageSize",2);
    List<User> userByLimit = mapper.getUserByLimit(map);
    for (User user : userByLimit) {
        System.out.println(user);
    }
}

8、注解开发

8.1、面向接口编程

接口应该是定义(规范,约束)和实现(名实分离的原则)的分离

接口的本身反应了系统设计人员对系统的抽象理解

  • 第一类是对一个个体对的抽象形成一个抽象体
  • 第二类是对一个个体某一个方面的抽象,形成一个抽象面

一个体可有多个抽象面

8.2、注解开发

  1. 注解在接口上实现
 @Select("select * from mybatis.user")
List<User> getUser();
  1. 在核心配置文件中绑定接口

    <!--    绑定接口-->
        <mappers>
            <mapper class="com.xiao.Dao.UserMapper"/>
        </mappers>
    
    1. 测试

本质:反射机制实现

底层:动态代理

请添加图片描述

mybatis执行流程

Resources获取加载全局配置文件---->getResourceAsStream流---->实例化SQLSessionFactoryBuilder构造器---->解析配置文件XMLConfigBuilder---->Configuration所有的配置信息---->SqlSessionFactory实例化---->transational事务管理器---->executor执行器(进行增删改查的具体操作 )---->创建sqlsession---->实现CRUD(增删改查)---->查看是否成功---->提交事务

8.3、CRUD

在工具类中实现自动提交事务

  @Select("select * from mybatis.user")
   List<User> getUser();
//    Param方法存在多个参数,在所有的参数前面必须就加上
    @Select("select * from  mybatis.user where  id=#{id}")
    User  getUserById(@Param("id") int id);
    @Insert("insert into mybatis.user(id,name,password) values(#{id},#{name},#{pwd})")
    int  addUser(User user);
    @Update("update mybatis.user set name=#{name},password=#{pwd} where id=#{id}")
    int updateUser(User user);
    @Delete("delete from mybatis.user where id=#{id}")
    int deleteUser(@Param("id")int id);

我们必须要将接口注册到我们的核心配置文件中

@Param(“id”)

  • 基本类型的参数或者string类型,需要加上
  • 引用类型不需要加
  • 如果制有一个基本类型的话,可以忽略
  • 我们在SQL中引用的就是我们这里的@param()中的设定的属性名

9. Lombok

@Setter :注解在类或字段,注解在类时为所有字段生成setter方法,注解在字段上时只为该字段生成setter方法。

@Getter :使用方法同上,区别在于生成的是getter方法。

@ToString :注解在类,添加toString方法。

@EqualsAndHashCode: 注解在类,生成hashCode和equals方法。

@NoArgsConstructor: 注解在类,生成无参的构造方法。

@RequiredArgsConstructor: 注解在类,为类中需要特殊处理的字段生成构造方法,比如final和被@NonNull注解的字段。

@AllArgsConstructor: 注解在类,生成包含类中所有字段的构造方法。

@Data: 注解在类,生成setter/getter、equals、canEqual、hashCode、toString方法,如为final属性,则不会为该属性生成setter方法。

@Slf4j: 注解在类,生成log变量,严格意义来说是常量。

10.多对一处理

关联:多个学生关联一个老师【多对一】

集合:一个老师,有很多学生【一对多】

mybatis-6

测试环境搭建

  1. 导入lombok

  2. 新建实体类teacher,student

  3. 建立Mapper接口

  4. 在核心配置文件mybatis-config配置绑定注册Mapper.xml

  5. 测试查询是否成功

按照查询嵌套处理

方式一

//StudentMapper.xml
<resultMap id="stu" type="student">
                        <result property="id" column="id"/>
                        <result property="name" column="name"/>
        <!--复杂的对象是单独处理,对象是使用association,集合使用connection-->
                        <association property="teacher" column="tid" javaType="teacher" select="com.xiao.Dao.TeacherMapper.getTeacher"/>
</resultMap>
                <select id="getStudent" resultMap="stu">
                select  * from student;
                </select>
</mapper>
//TeacherMapper.xml
<mapper namespace="com.xiao.Dao.TeacherMapper">
    <select id="getTeacher" resultType="teacher">
          select * from teacher where id=#{tid}
  </select>

按照结果嵌套处理

方式二

       <select id="getStudent2" resultMap="stu2">
               select s.id,s.name,t.name tname from  student s,teacher t where s.tid=t.id;
       </select>
        <resultMap id="stu2" type="student">
                <result property="id" column="id"/>
                <result property="name" column="name"/>
                <association property="teacher"  javaType="teacher">
                    <result property="name" column="tname"/>
                </association>
        </resultMap>

mysql多对一查询方式:

  • 子查询
  • 联表查询

11、一对多处理

mybatis-7

搭建环境

实体类

@Data
@NoArgsConstructor
@AllArgsConstructor
public class teacher {
    private int id;
    private String name;
//    一个老师拥有多个学生
    private List<student> student;

}

结果嵌套处理

    <resultMap id="tea" type="teacher">
        <result property="id" column="tid"/>
        <result property="name" column="tname"/>
<!--        collection集合,javaType="" 指定属性的类型
            集合中的泛型信息,我们使用ofType获取
-->
        <collection property="student" ofType="student">
            <result property="id" column="id"/>
            <result property="name" column="name"/>
            <result property="tid" column="tid"/>
        </collection>
    </resultMap>
    <select id="getTeacher1" resultMap="tea">
       select s.id,s.name,t.name tname,t.id tid from student s,teacher t where s.tid=t.id and t.id=#{id};
    </select>

查询嵌套处理

TeacherMapper.xml

      <select id="getTeacher2" resultMap="tea">
        select * from mybatis.teacher where id=#{id}
    </select>
    <resultMap id="tea" type="teacher">
        <collection property="students" column="id" javaType="ArrayList" ofType="student" select="com.xiao.Dao.StudentMapper.getStudent"/>
    </resultMap>
</mapper>

StudentMapper.xml

        <select id="getStudent" resultType="student">
        select * from mybatis.student  where tid=#{id};
</select>

小结

  1. 关联- association【多对一】
  2. 集合-connection【一对多】
  3. javaType & ofType
    • javaType 用来指定实体类中属性的类型
    • ofType 用来指定到list或者集合中的pojo类型,泛型中的约束类型

注意点:

  • 保证SQL的可读性
  • 注意一对多和多对一中,属性名和字段的问题
  • 使用日志,建议使用log4j

12、动态SQL

动态SQL指根据不同的条件生成不同的SQL语句

动态 SQL 是 MyBatis 的强大特性之一。如果你使用过 JDBC 或其它类似的框架,你应该能理解根据不同条件拼接 SQL 语句有多痛苦,例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。

搭建环境

CREATE TABLE `blog`(
`id` VARCHAR(50) NOT NULL COMMENT '博客id',
`title` VARCHAR(100) NOT NULL COMMENT '博客标题',
`author` VARCHAR(30) NOT NULL COMMENT '博客作者',
`create_time` DATETIME NOT NULL COMMENT '创建时间',
`views` INT(30) NOT NULL COMMENT '浏览量'
)ENGINE=INNODB DEFAULT CHARSET=utf8;
  1. 导包
  2. 编写配置文件
  3. 编写实体类
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class blog {
    private String id;
    private  String title;
    private  String author;
    private Date createTime;//属性名与字段名不一致
    private  int views;
}

if 判断

编写实体类对应的Mapper接口和Mapper.xml

public interface blogMapper {
     int addBlog(blog blog);
//     查询博客
     List<blog> queryBlog(Map map);
}
<insert id="addBlog" parameterType="blog">
    insert into blog(id,title,author,create_time,views)  values(#{id},#{title},#{author},#{createTime},#{views});
</insert>
<select id="queryBlog" parameterType="map" resultType="blog">
    select * from blog where 1=1
    <if test="title != null">
        and title like #{title}
    </if>
    <if test="author !=null">
        and author like #{author}
    </if>
</select>

choose、when、otherwise

<select id="queryBlogChoose" resultType="blog" parameterType="map">
    select * from blog
    <where>
    <choose>
        <when test="title != null">
            title=#{title}
        </when>
        <when test="author != null">
            and author=#{author}
        </when>
        <otherwise>
            and views=#{views}
        </otherwise>
    </choose>
    </where>
</select>

trim、where、set

<select id="queryBlogChoose" resultType="blog" parameterType="map">
    select * from blog
    <where>
        <if test="title != null">
            title=#{title}
        </if>
        <if test="author != null">
            and author=#{author}
        </if>
    </where>
</select>

set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)。

<update id="updateAuthorIfNecessary">
  update Author
    <set>
      <if test="username != null">username=#{username},</if>
      <if test="password != null">password=#{password},</if>
      <if test="email != null">email=#{email},</if>
      <if test="bio != null">bio=#{bio}</if>
    </set>
  where id=#{id}
</update>

动态SQL,在是SQL层面执行一个逻辑代码

forEach

select * from user where 1=1 and 
<foreach item="id" index="index" collection="ids"
 		open="(" separator="," close=")" </froeach>

请添加图片描述

<select id="queryBlogFor" parameterType="map" resultType="blog">
    select * from blog
    <where>
        <foreach collection="ids" item="id" open="and (" separator="or" close=")">
            id=#{id}
        </foreach>
    </where>
</select>

SQL脚本

将一些功能的部分抽取出来,方便使用

使用SQL标签抽取公共的部分

<sql id="author-title">
    <if test="title != null">
        and title like #{title}
    </if>
    <if test="author !=null">
        and author like #{author}
    </if>
</sql>

//在使用的地方使用include标签引用
//应用部分
  <include refid="author-title"/>

注意事项:

最好基于单表来定义SQL片段

不要存在where标签

动态SQL就是在拼接SQL语句,保证SQL的正确性,按照SQL的格式,排列组合

13、缓存

mybatis缓存

mybatis包含一个强大的查询缓存特性,方便定制和配置缓存。缓存可以极大地提升查询效率

mybatis系统默认定义了两极缓存:一级缓存和二级缓存

  • 默认下,只有一级缓存开启(SqlSession级别的缓存,以为是本地缓存)
  • 二级缓存需要手动开启和配置,它是基于namespace级别的缓存。
  • 为了提高扩展性,mybatis定义了缓存接口cache。我们可以通过实现cache接口来定义二级缓存

一级缓存

  1. 与数据库同一次会话期间查询到的数据会放在本地缓存中
  2. 如果需要获取相同的数据,直接从缓存中拿,不需要去查询数据库

手动清理缓存

sqlSession.clearCache();

二级缓存

一级缓存作用域太低,诞生二级缓存

基于namespace级别的缓存,一个名称空间,对应一个二级缓存

工作机制:

  • 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中
  • 如果当前会话关闭,这个会话对应的一级缓存就没有了,但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中
  • 新的会话查询信息,可以从二级缓存中获取内容
<select id="queryBlogFor" parameterType="map" resultType="blog">
    select * from blog
    <where>
        <foreach collection="ids" item="id" open="and (" separator="or" close=")">
            id=#{id}
        </foreach>
    </where>
</select>

SQL脚本

将一些功能的部分抽取出来,方便使用

使用SQL标签抽取公共的部分

<sql id="author-title">
    <if test="title != null">
        and title like #{title}
    </if>
    <if test="author !=null">
        and author like #{author}
    </if>
</sql>

//在使用的地方使用include标签引用
//应用部分
  <include refid="author-title"/>

注意事项:

最好基于单表来定义SQL片段

不要存在where标签

动态SQL就是在拼接SQL语句,保证SQL的正确性,按照SQL的格式,排列组合

13、缓存

mybatis缓存

mybatis包含一个强大的查询缓存特性,方便定制和配置缓存。缓存可以极大地提升查询效率

mybatis系统默认定义了两极缓存:一级缓存和二级缓存

  • 默认下,只有一级缓存开启(SqlSession级别的缓存,以为是本地缓存)
  • 二级缓存需要手动开启和配置,它是基于namespace级别的缓存。
  • 为了提高扩展性,mybatis定义了缓存接口cache。我们可以通过实现cache接口来定义二级缓存

一级缓存

  1. 与数据库同一次会话期间查询到的数据会放在本地缓存中
  2. 如果需要获取相同的数据,直接从缓存中拿,不需要去查询数据库

手动清理缓存

sqlSession.clearCache();

二级缓存

一级缓存作用域太低,诞生二级缓存

基于namespace级别的缓存,一个名称空间,对应一个二级缓存

工作机制:

  • 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中
  • 如果当前会话关闭,这个会话对应的一级缓存就没有了,但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中
  • 新的会话查询信息,可以从二级缓存中获取内容
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值