栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【Mybatis】Mybatis基础(下)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【Mybatis】Mybatis基础(下)

目录

1、动态SQL

1.1、搭建环境

1.2、if

1.3、trim、where、set

1.3.1、Where

1.3.2、Trim

1.3.3、Set

1.4、choose、when、otherwise

1.5、foreach

2、缓存(了解即可)

2.1、Mybatis缓存

2.2、一级缓存

2.3、二级缓存


1、动态SQL

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

元素种类:

  • if

  • choose(where,set)

  • trim(where,set)

  • foreach

1.1、搭建环境
  1. 创建一张blog博客表

CREATE TABLE `blogs` (
  `blogid` char(32) NOT NULL COMMENT '博客id',
  `title` varchar(100) DEFAULT NULL COMMENT '博客标题',
  `author` varchar(50) DEFAULT NULL COMMENT '作者',
  `type` varchar(50) DEFAULT NULL COMMENT '博客类型',
  `publishDateTime` datetime DEFAULT NULL COMMENT '出版日期',
  `content` varchar(300) DEFAULT NULL COMMENT '内容',
  `isDisplay` char(1) DEFAULT NULL COMMENT '是否显示',
  `readCount` int(11) DEFAULT NULL COMMENT '阅读量',
  `image` varchar(100) DEFAULT NULL COMMENT '图片',
  PRIMARY KEY (`blogid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

数据库里面自己随机插入数据就行,推荐使用com.github.javafaker.Faker这个去导数据,这里不做详细介绍。

  1. 创建Mybatis基础工程

    1. 导包(跟前面一样)

    2. 编写配置文件(db.properties和mybatis-config.xml配置文件基本不变)

    注意:

    db.properties中的数据库名要改成当前数据库名

  2. mybatis-config.xml中要修改mapper映射器

    1. 编写实体类

    2. @Data
      public class blog {
          private String id;
          private String title;
          private String auther;
          private String type;
          private Date publishDateTime;
          private String content;
          private String isDisplay;
          private int redCount;
          private String imge;
      }
    3. 编写工具类

    //SqlSessionFactory --> SqlSession
    public class MybatisUtils {
        private static SqlSessionFactory sqlSessionFactory;
        static{
            try {
                //使用mybatis第一步:获取sqlSessionFactory对象
                String resource = "mybatis-config.xml";
                InputStream inputStream;
                inputStream = Resources.getResourceAsStream(resource);
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    ​
        //有了sqlSessionFactory就可以获取sqlSession的实例
        //sqlSession完全包含了面向数据库执行SQL命令所需的方法
        public static SqlSession getsqlSession(){
            return sqlSessionFactory.openSession(true);
        }
    }
    1. 编写实体类对应的Mapper接口和Mapper.xml文件

    2. 结构

1.2、if

使用动态 SQL 最常见情景是根据条件包含 where 子句的一部分。比如查询名为斯蒂芬且博客题目不为空的博客信息:

1.在BlogMapper接口中定义查询方法:

public interface BlogMapper {
    //搜索斯蒂芬作者是否含有标题为123的博客
    //对应的SQL语句:select * from blogs where author = '斯蒂芬' and title like '123';
    public blog selectBlogif(String title);
}

2.在BlogMapper.xml中写对应的SQL语句以及if语句


    

    select * from blogs
    where author = '斯蒂芬'
    
        and type like #{type}
    
    
        and title like #{title}
    

测试:

@Test
public void selectBlogif(){
    SqlSession sqlSession = MybatisUtils.getsqlSession();
    BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
    Map map = new HashMap();
    map.put("type","software");
    map.put("title","123");
    List blogs = mapper.selectBlogif(map);
    System.out.println(blogs);
    sqlSession.close();
}

结果:

Opening JDBC Connection
    Created connection 849373393.
    ==>  Preparing: select * from blogs where author = '斯蒂芬' and type like ? and title like ? 
        ==> Parameters: software(String), 123(String)
            <==    Columns: blogid, title, author, type, publishDateTime, content, isDisplay, readCount, image
                <==        Row: e9118e01ed3d4fc49aa9cb448185df11, 123, 斯蒂芬, software, 2021-11-09 06:36:09.0, wrewqefasdfsafsadf, 1, 242, images/small-image.jpg
                    <==      Total: 1
                        [blog(id=e9118e01ed3d4fc49aa9cb448185df11, title=123, author=斯蒂芬, type=software, publishDateTime=Tue Nov 09 06:36:09 CST 2021, content=wrewqefasdfsafsadf, isDisplay=1, redCount=0, imge=null)]
                        Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@32a068d1]
                        Returned connection 849373393 to pool.

1.3、trim、where、set

这次我们将 “author= ‘斯蒂芬’” 设置成动态条件,看看会发生什么。


    select * from blogs
    where   
    
        and author = '斯蒂芬'
    
    
        and type like #{type}
    
    
        and title like #{title}
    

结果为:

Opening JDBC Connection
    Created connection 849373393.
    ==>  Preparing: select * from blogs where and type like ? and title like ? 
        ==> Parameters: software(String), 123(String)

可以看到,SQL语句变成了select * from blogs where and type like ? and title like ?

正常的应该是select * from blogs where 1=1 and ... and ...,需要一个恒等式来连接SQL语句,但每次这样写有点麻烦,就用到了where元素

1.3.1、Where

可以将上面的SQL改正:


    select * from blogs
    
        
            and author = '斯蒂芬'
        
        
            and type like #{type}
        
        
            and title like #{title}
        
    

where 元素只会在子元素返回任何内容的情况下才插入 “WHERe” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。如果传递的值为空,则where后面的SQL语句会自动删除。

1.3.2、Trim

如果 where 元素与你期望的不太一样,你也可以通过自定义 trim 元素来定制 where 元素的功能。比如,和 where 元素等价的自定义 trim 元素为:


    -->
        and author = '斯蒂芬'
    
    
        and type like #{type}
    
    
        and title like #{title}
    

上述例子会移除所有 prefixOverrides 属性中指定的内容(第一个and或者or),并且插入 prefix 属性中指定的内容。

1.3.3、Set

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


    update blogs
    
        title=#{title},
        author=#{author}
    
    where blogid=#{id}

结果:

Opening JDBC Connection
    Created connection 1891546521.
    ==>  Preparing: update blogs SET title=?, author=? where blogid=? 
        ==> Parameters: 已修改这个标题(String), 被修改的作者(String), 0cfc526c437c4055b542b0e3e302d787(String)
            <==    Updates: 1
                Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@70beb599]
                Returned connection 1891546521 to pool.

set 元素等价的自定义 trim 元素


    update blogs
    
        title=#{title},
        author=#{author}
    
    where blogid=#{id}

1.4、choose、when、otherwise

有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。

还是上面的例子,但是策略变为:传入了 “title” 就按 “title” 查找,传入了 “author” 就按 “author” 查找的情形。若两者都没有传入,就返回类型为 software 的 BLOG。