MyBatis狂神说学习笔记

MyBatis

1.MybatisDemo
  • 导入依赖,编写xml配置文件

     <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.5</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.32</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    
    <?xml version="1.0" encoding="UTF-8" ?>
            <!DOCTYPE configuration
                    PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
                    "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <!--核心配置文件-->
    <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/activitycenter?	   useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                    <property name="username" value="root"/>
                    <property name="password" value="root"/>
                </dataSource>
            </environment>
        </environments>
        
        <!--每一个Mapper.xml都需要在Mybatis核心配置文件中注册-->
        <mappers>
        <mapper resource="com/wyf/mapper/UserMapper.xml"/>
    	</mappers>
        
    </configuration>
    
  • 编写mybatis工具类

    //SqlSessionFactory
    public class MybatisUtils {
        private static SqlSessionFactory sqlSessionFactory;
        static{
            try {
                //使用Mybatis第一步获取sqlSessionFactory对象
                String resource = "mybatis-config.xml";
                InputStream inputStream = Resources.getResourceAsStream(resource);
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        //既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
        //SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句。
        public static SqlSession getSqlSession(){
            return sqlSessionFactory.openSession();
        }
    }
    
  • 编写代码

    • 编写实体类

      public class Person {
          private int id;
          private String name;
          private String password;
      
          public Person() {
          }
      
          public Person(int id, String name, String password) {
              this.id = id;
              this.name = name;
              this.password = password;
          }
       }
      
    • 编写Mapper接口

      public interface UserMapper {
          List<Person> getUserList();
      }
      
    • 接口实现类由原来的UserDaoImpl转变为一个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">
      
          <!--namespace=绑定一个对应的Mapper接口-->
      <mapper namespace="com.wyf.mapper.UserMapper">
          
          <!--select id后面的名字对应接口的方法名-->
          <select id="getUserList" resultType="com.wyf.pojo.Person">
          select * from person
        </select>
      </mapper>
      
  • 测试

    • 控制台报

      org.apache.ibatis.binding.BindingException: Type interface com.wyf.mapper.UserMapper is not known to the MapperRegistry.

      UTF-8可能也会出现问题,需要改成utf8

      • 解决:需要在核心配置文件中注册mappers
<!--每一个Mapper.xml都需要在Mybatis核心配置文件中注册-->
<mappers>
    <mapper resource="com/wyf/mapper/UserMapper.xml"/>
</mappers>
  • 还要注意Maven资源导出的问题

    <!--pom.xml-->
    <!--在build中配置resources,来防止我们资源导出失败的问题-->
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>
    
    public class UserMapperTest {
        @Test
        public void test(){
            //第一步,获取SqlSession对象
            SqlSession sqlSession = MybatisUtils.getSqlSession();
    
            //getMapper
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            List<Person> userList = userMapper.getUserList();
            for (Person person : userList) {
                System.out.println(person);
            }
            //关闭SqlSession
            sqlSession.close();
        }
    }
    
2.CRUD(增删改查)
1.namespace

​ namespace中的包名要和Mapper接口的包名一致

2.select、insert、update、delete

​ 选择,查询语句;

  • id:就是对应namespace中的方法名

  • resultType:Sql语句执行的返回值!

  • parameterType:参数类型!

1.编写接口

public interface UserMapper {
    //查询全部用户
    List<User> getUserList();

    //根据Id查询用户
    User getUserById(int id);

    //insert一个用户
    int addUser(User user);

    //修改用户
    int updateUser(User user);

    //删除一个用户
    int deleteUser(int id);
}

2.编写对应mapper中的sql语句

<?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=绑定一个对应的Mapper接口-->
<mapper namespace="mapper.UserMapper">

    <!--select id后面的名字对应接口的方法名-->
    <select id="getUserList" resultType="pojo.User">
        select * from user
     </select>

    <select id="getUserById" parameterType="int" resultType="pojo.User">
        select * from user where id = #{id}
    </select>

    <insert id="addUser" parameterType="pojo.User">
        insert  into demo.user (id,name,pwd) values (#{id},#{name},#{pwd});
    </insert>
    
    <update id="updateUser" parameterType="pojo.User">
        update demo.user set name = #{name},pwd= #{pwd} where id = #{id};
    </update>

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

3.测试(增删改需要提交事务)

//我们可以在工具类创建的时候实现自动提交事务
public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession(true);
    }
public class Test01 {
    //查询所有
    @Test
    public void test(){
        //第一步,获取SqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //getMapper
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = userMapper.getUserList();
        for (User person : userList) {
            System.out.println(person);
        }

        //关闭SqlSession
        sqlSession.close();
    }
    
    //根据用户Id查询用户
    @Test
    public void getUserById(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User userById = mapper.getUserById(1);
        System.out.println(userById);
        sqlSession.close();
    }

    //增加用户
    @Test
    public void addUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.addUser(new User(5, "111", "123456"));
        sqlSession.commit();
        sqlSession.close();
    }
    //根据用户Id更新用户
    @Test
    public void updateUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.updateUser(new User(1,"王运发","88888888"));
        sqlSession.commit();
        sqlSession.close();
    }

    //根据Id删除用户
    @Test
    public void deleteUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.deleteUser(5);
        sqlSession.commit();
        sqlSession.close();
    }
}
4.万能的Map

Map传递参数,直接在sql取出key即可

对象传递参数,直接在sql中取出对象属性即可

Mapper接口层中只有一个基本类型参数的情况下,可以直接在sql中取到

多个参数用Map,或者注解!

	
	//通过Map形参类型添加用户(UserMapper.interface)
    int addUser2(Map<String,Object> map);
    
    //xml文件
    <insert id="addUser2" parameterType="map">
        insert  into user (id,name,pwd) values (#{userId},#{userName},#{userPwd});
    </insert>
    
     @Test
    //通过Map方式添加用户
    public void addMapUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("userId",66);
        //map.put("userName","集合");//可以不用给对象的所有属性赋值
        map.put("userPwd",12121);
        mapper.addUser2(map);
        sqlSession.commit();
        sqlSession.close();
    }
5.模糊查询
<select id="getUserLike" resultType="pojo.User">
      select * from user where name like "%"#{value}"%";
</select>

@Test
//模糊查询
public void getUserLike(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    List<User> userLike = mapper.getUserLike("王");//List<User> userLike = mapper.getUserLike("%王%"); like #{value};
    for (User user : userLike) {
    System.out.println(user);
	}
	sqlSession.close();
}
4.配置解析
1.核心配置文件
  • mybatis-config.xml
  • Mybatis的配置文件包含了深深影响Mybatis行为的设置和属性信息
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)
2.environments(环境配置)
<environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
</environments>
3.properties(属性)

编写一个配置文件db.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/demo?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useUnicode=true&useSSL=false
username=root
password=root

在核心配置文件引入

<properties resource="db.properties">
        <property name="username" value="root"/>
        <property name="password" value="root"/>
</properties>
  • 可以直接引入外部文件
  • 可以在其中增加一些属性配置
  • 如果两个文件有同一字段,例如username和password,优先使用外部配置文件(db.properties)中的属性
4.typeAliases(类型别名)
  • 类型别名是为Java类型设置一个短的名字
  • 存在的意义仅在于用来减少类完全限定名的冗余
//场景:pojo包下有一个User实体类
//方式一
<!--typeAlias给实体类起别名-->
<typeAliases>
    <typeAlias type="pojo.User" alias="User"/>
</typeAliases>

//优化前
<select id="getUserList" resultType="pojo.User">
        select * from user
</select>
//优化后
 <select id="getUserList" resultType="User">
        select * from user
</select>

//方式二
  <!--扫描实体类的包名,默认别名就是实体类的类名,首字母小写-->
    <typeAliases>
        <package name="pojo"/>
    </typeAliases>
//优化前
<select id="getUserList" resultType="pojo.User">
        select * from user
</select>
//优化后
 <select id="getUserList" resultType="user">
        select * from user
</select>

实体类比较少,使用第一种,实体类比较多,建议使用第二种,第一种可以DIY别名,第二种只能通过在实体类上使用@Alias(user)注解起别名

5.settings(设置)

Mybatis中极为重要的调整设置,他们会改变Mybatis的运行时的行为

6.其他配置
  • typeHandlers(类型处理器)
  • objectFactory(对象工厂)
  • plugins(插件)
    • mybatis-generator-core
    • mybatis-plus
    • 通用mapper
7.映射器(mappers)

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

方式一:资源文件注册(推荐)

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

方式二:使用class文件绑定注册

<!--每一个Mapper.xml都需要在Mybatis核心配置文件中注册-->
<mappers>
  <mapper class="mapper.UserMapper"/>
</mappers>

注意点:

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

方式三:使用扫描包进行注入绑定

<!--每一个Mapper.xml都需要在Mybatis核心配置文件中注册-->
<mappers>
     <package name="mapper"/>
</mappers>

注意点:

  • 接口和他的Mapper配置文件必须同名
  • 接口和他的Mapper配置文件必须在同一个包下
8.生命周期和作用域

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

SqlSessionFactoryBuilder:

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

SqlSessionFactory:

  • 说白了可以理解为:数据库连接池

  • SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例。

  • 最简单的就是使用单例模式或者静态单例模式。

SqlSession

  • 连接到连接池的一个请求
  • SqlSession的实例不是线程安全的,因此不能被共享,所以它最佳的作用域是请求或方法作用域
  • 用完之后需要赶紧关闭,否则资源被占用!

9.解决属性名和字段名不一致的问题

问题:实体类属性名跟数据库字段名名称不一致

select * from user where id = #{id}

//类型处理器

select id,name,pwd from user where id = #{id}

解决:

  • 起别名

    <select id = "getUserById" resultType="pojo.User">
    	select id,name,pwd as password from user where id = #{id}
    </select>
    
  • reslutMap结果集映射

id name pwd
id name password
 <!--column数据库中的字段, property实体类中的属性-->
<resultMap id="UserMap" type="pojo.User">
     <!--column和property相同就不需要映射了-->
   <!-- <result column="id" property="id"/>-->
    <result column="name" property="name"/>
    <result column="pwd" property="password"/>
</resultMap>

<select id="getUserById"  resultMap="UserMap">
    select * from user where id = #{id}
</select>
5.日志
5.1日志工厂

如果一个数据库操作,出现了异常,我们需要排错。日志就是最好的助手!

曾经:sout、debug

  • SLF4J |
  • LOG4J(3.5.9 起废弃)【掌握】
  • LOG4J2【掌握】
  • JDK_LOGGING
  • COMMONS_LOGGING
  • STDOUT_LOGGING 【掌握】
  • NO_LOGGING
5.2 STDOUT_LOGGING 标准日志输出
<--要注意settings在核心配置文件中的上下顺序-->
<settings>
     <setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>

5.3 LOG4J

​ 1.导入log4j的依赖

​ 2.创建一个log4j.properties配置文件进行配置log4j的属性

  1. 配置log4j的实现

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

4.简单使用

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

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

    static Logger logger = Logger.getLogger(UserDaoTest.class)
    
  • 日志级别

    logger.info("info:进入了testLog4j");
    logger.debug("debug:进入了testLog4j");
    logger.error("error:进入了testLog4j");
    
6.分页

思考:为什么要分页?

  • 减少数据的处理量

使用Limit实现分页,从第几个数据开始查询几条

语法:SELECT * FROM `user` LIMIT 0,3;//从第一条记录开始查询三条数据
SELECT * FROM `user` LIMIT 4;//查询前四条记录

使用Mybatis实现分页,核心SQL

​ 1.接口

 //分页
 List<User> getUserByLimit(Map<String,Integer> map);

​ 2.Mapper.xml

<resultMap id="UserMap" type="pojo.User">
</resultMap>
<select id="getUserByLimit"  parameterType="map" resultMap="UserMap">
select * from user limit #{startIndex},#{pageSize}
</select>

​ 3.测试

 @Test
    public void test(){
        //第一步,获取SqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //getMapper
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        Map<String,Integer> map = new HashMap<String,Integer>();
        map.put("startIndex",0);
        map.put("pageSize",2);
        List<User> userByLimit = userMapper.getUserByLimit(map);

        for (User user : userByLimit) {
            System.out.println(user);
        }
        //关闭SqlSession
        sqlSession.close();
    }

RowBounds分页(不使用SQL实现分页)

1.接口

//RowBounds分页
List<User> getUserByRowBounds(Map<String,Integer> map);

2.mapper.xml

<resultMap id="UserMap" type="pojo.User"></resultMap>
<select id="getUserByRowBounds"  parameterType="map" resultMap="UserMap">
	select * from user
</select>

3.测试

RowBounds rowBounds = new RowBounds(1, 2); 
List<User> list = sqlSession.selectList("mapper.UserMapper.getUserByRowBounds",null,rowBounds);
7.使用注解开发

1.注解在接口上实现

public interface UserMapper {
@Select("select * from user")
List<User> getUsers();

@Select("select * from user where id = #{id}")
User getUserById(@Param("id") int id);

@Insert("insert into user(id,name,pwd) values (#{id},#{name},#{pwd})")
int insertUser(User user);

@Update("update user set name=#{name},pwd=#{password} where id = #{id}")
int updateUser(User user);

@Delete("delete from user where id = #{wid}")
int deleteUser(@Param("wid") int id);
}

2.需要在核心配置文件中绑定接口

<!--绑定接口-->
<!--在企业开发中会使用包名通配符的方式,避免每次都需要绑定接口-->
<mappers>
    <mapper class="mapper.UserMapper"/>
</mappers>

3.测试

 @Test
    public void test01(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //测试了删除
        int i = mapper.deleteUser(8);
        System.out.println(i);

    }

本质:反射机制实现

底层:动态代理

关于@Param()注解

  • 基本类型的参数或者String类型,需要加上
  • 引用类型不需要加
  • 如果只有一个基本类型的话,可以忽略,但是建议加上
  • 我们在SQL中引用的就是我们在 @Param()中设定的属性名,例如下面的注解删除demo
    • @Delete(“delete from user where id = #{wid}”)
      int deleteUser(@Param(“wid”) int id);
8.多对一处理

比如:多个学生拥有一个老师

  • 方式一: 子查询
//Srudent实体类中有了Teacher这个属性
public class Student {
    private int id;

    private String name;

    private Teacher teacher;
}
<!--
        思路:
        1.查询所有学生信息
        2.根据查询出来的学生的tid,寻找对应的老师!
    -->
    <select id="getStudent" resultMap="StudentTeacher">
            SELECT * from student
    </select>

    <resultMap id="StudentTeacher" type="pojo.Student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
    <!-- 复杂的属性,我们需要单处理
         对象:association
         集合:collection
    -->
        //column为student表中与teacher表中关联的字段,通过student表中的tid查询对应的老师信息
        <association property="teacher" column="tid" javaType="pojo.Teacher" 		     		 select="getTeacher"/>
    </resultMap>

    <select id="getTeacher" resultType="pojo.Teacher">
        select * from teacher where id = #{id}
    </select>
  • 方式二:连表查询(推荐(数据量小))
 <!--按照结果嵌套处理-->
    <select id="getStudent2" resultMap="StudentTeacher2">
        SELECT s.id,s.`name`,t.name AS tname FROM student s,teacher t WHERE s.tid = t.id
    </select>

    <resultMap id="StudentTeacher2" type="pojo.Student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <association property="teacher" javaType="pojo.Teacher">
            <result property="name" column="tname"/>
        </association>
    </resultMap>
9.一对多处理

比如:一个老师对应多个学生

对于老师而言就是一对多的关系!

public class Teacher {
    private int id;

    private String name;

    //一个老师拥有多个学生
    private List<Student> students;
}
  • 方式一:按照结果嵌套处理(推荐,写出一个复杂sql即可)
<!--按照结果嵌套查询-->
<select id="getTeacher" resultMap="TeacherStudent">
    SELECT s.id sid,s.name sname, t.name tname,t.id tid FROM student s,teacher t WHERE s.tid = t.id and t.id = #{tid}
</select>
<resultMap id="TeacherStudent" type="pojo.Teacher">
    <result property="id" column="tid"/>
    <result property="name" column="tname"/>
<!--复杂的属性我们需要单独处理,对象:association 集合:collection
    javaType=""指定属性的类型
    集合中的泛型信息,我们使用ofType获取
-->
    <collection property="students" ofType="pojo.Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <result property="tid" column="tid"/>
    </collection>
</resultMap>
  • 方式二:按照查询嵌套处理
<select id="getTeacher2" resultMap="TeacherStudent2">
        select * from teacher where id = #{tid}
    </select>

    <resultMap id="TeacherStudent2" type="pojo.Teacher">
        <collection property="students" javaType="ArrayList" ofType="pojo.Student" select="getStudentByTeacherId" column="id"/>
    </resultMap>

    <select id="getStudentByTeacherId" resultType="pojo.Student">
        select * from student where tid = #{tid}
    </select>
  • 小结
    • 关联-association【多对一】
    • 集合-collection【一对多】
    • javaType(用来指定实体类中属性的类型) & ofType(指泛型中的约束类型)

10.动态SQL

什么是动态SQL? 就是根据不同的条件生成不同的SQL语句

  • 环境搭建

1.导包

<dependencies>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.22</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13.2</version>
        <scope>test</scope>
    </dependency>
</dependencies>

2.编写配置文件

<!--允许将数据库字段转换为驼峰命名的实体类属性-->
  <settings>
    <setting name="mapUnderscoreToCamelCase" value="true"/> 
  </settings>
 <mappers>
    <mapper class="mapper.BlogMapper"/>
 </mappers>

3.编写实体类

@Data
@AllArgsConstructor
public class Blog {
    private String id;
    private String title;
    private String author;
    private Date createTime;
    private String views;
}

4.编写Mapper接口和Mapper.xml文件

//插入数据
int addBlog(Blog blog);

<insert id="addBlog" parameterType="pojo.Blog">
    insert into blog (id, title, author, create_time, views)
    values (#{id},#{title},#{author},#{createTime},#{views});
</insert>
If的使用
//根据title和author限制条件查询
List<Blog> queryBlogIf(Map map);
 <select id="queryBlogIf" parameterType="map" resultType="pojo.Blog">
    select * from blog where 1=1
      <if test="title != null">
           and title = #{title}
      </if>
      <if test="author != null">
           and author = #{author}
      </if>
    </select>
  @Test
    public void test(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        Map map = new HashMap();
        //可以同时限制两个查询条件
//      map.put("title","3333");
        map.put("author","333");
        List<Blog> blogs = mapper.queryBlogIf(map);
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
        sqlSession.close();
    }
choose(when,otherwise)
  • choose标签的使用,类似于Java关键字switch
<select id="queryBlogChoose" parameterType="map" resultType="pojo.Blog">
        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>
  • 测试(原理跟switch类似,从上至下,有满足的就走满足的那个条件)
@Test
    public void test(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        Map map = new HashMap();
        map.put("title","3333");
//        map.put("author","333");
        map.put("views","333");
        List<Blog> blogs = mapper.queryBlogChoose(map);
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
        sqlSession.close();
    }

trim(where,set)
  • where标签的使用
	//优化前 如果if中某个条件不成立会导致(where后面直接and)where and author=#{author}的报错情况
	<select id="queryBlogIf" parameterType="map" resultType="pojo.Blog">
   		 select * from blog where 
      <if test="title != null">
           and title = #{title}
      </if>
      <if test="author != null">
           and author = #{author}
      </if>
    </select>  

	//使用where标签就会避免这个问题
	<select id="queryBlogIf" parameterType="map" resultType="pojo.Blog">
        select * from blog
        <where>
            <if test="title != null">
                and title = #{title}
            </if>
            <if test="author != null">
                and author = #{author}
            </if>
        </where>
    </select>
  • set标签的使用
 <update id="updateBlog" parameterType="map">
      update blog
      <set>
          <if test="title != null">
              title = #{title},
          </if>
          <if test="author != null">
              author = #{author}
          </if>
          	  where id = #{id}
      </set>
    </update>

总结:所谓的动态sql,本还是sql语句,只是我们在sql层面,去执行一个逻辑代码

sql片段

有的时候我们可以将一些功能部分抽取出来,方便复用

1.使用sql标签抽取公共的部分

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

2.再有需要的地方使用include标签引用即可

 <select id="queryBlogIf" parameterType="map" resultType="pojo.Blog">
 	   select * from blog
    <where>
       <include refid="if-title-author"></include>
    </where>
 </select>

3.注意事项:

  • 最好基于单表来定义sql片段
  • 不要存在where标签
foreach
//查询第一二三号记录的博客
List<Blog> queryBlogForeach(Map map);
 <select id="queryBlogForeach" parameterType="map" resultType="pojo.Blog">
        select * from blog
        <where>
            <foreach collection="ids" item="id" open="(" separator="or" close=")">
                id = #{id}
            </foreach>
        </where>
  </select>
 @Test
    public void foreachTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);

        Map map = new HashMap();

        ArrayList<Integer> ids = new ArrayList<Integer>();
        ids.add(1);
        ids.add(2);
        ids.add(3);
        map.put("ids",ids);
        List<Blog> blogs = mapper.queryBlogForeach(map);

        for (Blog blog : blogs) {
            System.out.println(blog);
        }

        sqlSession.close();
    }
11.缓存(了解Mybatis缓存策略即可,目前会使用Redis作为缓存)

Mybatis系统中默认定义了两级缓存:一级缓存和二级缓存

  • 默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)
  • 二级缓存需要手动开启和配置,他是基于namespace级别的缓存
  • Mybatis定义了缓存接口Cache,我们可以通过Cache接口来定义二级缓存
一级缓存:
  • 一级缓存也叫本地缓存:Sqlsession
    • 与数据库同一次会话期间查询到的数据会放在本地缓存中
    • 如果再次获取相同的数据,直接从缓存中拿,不必在查询数据库
二级缓存
  • 二级缓存也叫全局缓存,由于一级缓存作用域低,所以诞生了二级缓存
  • 基于namespace级别的缓存,一个名称空间,对应一个二级缓存
  • 工作机制
    • 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中
    • 如果会话关闭了,这个会话对应的一级缓存就没了;会话关闭,一级缓存中的数据被保存到二级缓存中。
    • 新的会话查询信息,就可以从二级缓存中获取内容。
小节:
  • 只要开启了二级缓存,在同一个Mapper下就有效
  • 所有的数据都会先放在一级缓存中
  • 只有当会话关闭的时候,才会提交到二级缓存中
    r" close=“)”>
    id = #{id}


 @Test
    public void foreachTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);

        Map map = new HashMap();

        ArrayList<Integer> ids = new ArrayList<Integer>();
        ids.add(1);
        ids.add(2);
        ids.add(3);
        map.put("ids",ids);
        List<Blog> blogs = mapper.queryBlogForeach(map);

        for (Blog blog : blogs) {
            System.out.println(blog);
        }

        sqlSession.close();
    }
11.缓存(了解Mybatis缓存策略即可,目前会使用Redis作为缓存)

Mybatis系统中默认定义了两级缓存:一级缓存和二级缓存

  • 默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)
  • 二级缓存需要手动开启和配置,他是基于namespace级别的缓存
  • Mybatis定义了缓存接口Cache,我们可以通过Cache接口来定义二级缓存
一级缓存:
  • 一级缓存也叫本地缓存:Sqlsession
    • 与数据库同一次会话期间查询到的数据会放在本地缓存中
    • 如果再次获取相同的数据,直接从缓存中拿,不必在查询数据库
二级缓存
  • 二级缓存也叫全局缓存,由于一级缓存作用域低,所以诞生了二级缓存
  • 基于namespace级别的缓存,一个名称空间,对应一个二级缓存
  • 工作机制
    • 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中
    • 如果会话关闭了,这个会话对应的一级缓存就没了;会话关闭,一级缓存中的数据被保存到二级缓存中。
    • 新的会话查询信息,就可以从二级缓存中获取内容。
小节:
  • 只要开启了二级缓存,在同一个Mapper下就有效
  • 所有的数据都会先放在一级缓存中
  • 只有当会话关闭的时候,才会提交到二级缓存中
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值