总结MyBatis知识点

44 篇文章 7 订阅
23 篇文章 1 订阅

目录

1、 MyBatis是什么?

2、Mybatis解决哪些问题?

3、开始创建工程

【1】创建Maven项目

【2】pom.xml依赖

 【3】mybatis.xml依赖

【4】实体类

 【6】测试类

【7】发现一个BUG,Team.xml

【8】结果

 【9】改进,使用@Before@After

 4、日志的使用

【1】pom.xml

【2】log4j.properties

【3】mybatis.xml

【4】结果

 5、建造者设计模式介绍

6、#{} 和 ${}的区别

【1】#{}

【2】${}

7、动态SQL

更新

8、分页

【1】pom.xml

【2】mybatis.xml

【3】测试

9、Mybatis缓存

【1】 一级缓存

【2】二级缓存

【3】清空缓存的方式


1、 MyBatis是什么?

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

官网:mybatis – MyBatis 3 | 简介

2、Mybatis解决哪些问题

1 、数据库连接的创建、释放连接的频繁操作造成资源的浪费从而影响系统的性能。
2 SQL 语句编写在代码中,硬编码造成代码不容易维护,实际应用中 SQL 语句变化的可能性比较大,一旦变动就需要改变 java 类。
3 、使用 preparedStatement 的时候传递参数使用占位符,也存在硬编码,因为 SQL 语句变化,必须修改源码。
4 、对结果集的解析中也存在硬编码。

3、开始创建工程

【1】创建Maven项目

【2】pom.xml依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <!--自定义-->
    <groupId>com.qinluyu</groupId>
    <artifactId>Mybatis01</artifactId>
    <version>1.0-SNAPSHOT</version>
    <!--Mybatis-->
    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>
        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <!--mysql版本5-6之间-->
            <version>5.1.45</version>
        </dependency>
        <!--测试test-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <!--maven-->
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <!--jdk-->
                    <target>1.8</target>
                    <source>1.8</source>
                </configuration>

            </plugin>
        </plugins>
    </build>
</project>

 【3】mybatis.xml依赖

<?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/mybatis?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=false&amp;serverTimezone=GMT"/>
                <property name="username" value="${root}"/>
                <property name="password" value="${123}"/>
            </dataSource>
        </environment>
    </environments>
    <!--映射文件-->
    <mappers>
        <mapper resource="com.qinluyu.Dao.Team.xml"/>
    </mappers>
</configuration>

【4】实体类

public class Team {
    private Integer teamId;
    private String teamName;
    private String location;
    private Date createTime;
get/set方法
tostring方法

【5】实体类的映射文件

 【6】测试类

private String resource="mybatis.xml";
    @Test
    public void test02(){
        SqlSession sqlSession=null;
        try{
        Reader reader=Resources.getResourceAsReader(resource);
        SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(reader);//根据图纸创建出了工厂
        sqlSession=factory.openSession();
        //执行sql
        List<Team> list=sqlSession.selectList("com.qinluyu.Dao.Team.queryAll");
        //遍历结果
        for(Team team:list){
        System.out.println(team);
        }
        }catch(IOException e){
        e.printStackTrace();
        }finally{
        //关闭资源
        sqlSession.close();
        }

【7】发现一个BUG,Team.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">
<mapper namespace="com.qinluyu.pojo.Team">
    <!--查询,id为自定义名称,相当于dao-->
    <select id="queryAll" resultType="com.qinluyu.pojo.Team">

    <!--<select id="queryAll" resultMap="com.qinluyu.pojo.Team">-->此为BUG
        select * from team;
    </select>

</mapper>

【8】结果

 【9】改进,使用@Before@After

public class TestTeam {
    private String resource="mybatis.xml";
    private SqlSession sqlSession;
    @Test
    public void test02(){
        System.out.println("改进————,查询单个");
        Team team = sqlSession.selectOne("com.qinluyu.pojo.Team.queryOne", 1002);
        System.out.println(team);
    }
    @Before
    public void before(){
        Reader reader=null;
        try {
            reader=Resources.getResourceAsReader(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(reader);
        sqlSession=factory.openSession();
    }
    @After
    public void after(){
        sqlSession.close();
    }

 4、日志的使用

【1】pom.xml

<!--日志的使用-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

【2】log4j.properties

# Global logging configuration  info  warning  error
log4j.rootLogger=DEBUG,stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

【3】mybatis.xml

<!--注意顺序
    configuration (properties?, settings?, typeAliases?, typeHandlers?, objectFactory?, objectWrapperFactory?, reflectorFactory?, plugins?, environments?, databaseIdProvider?, mappers
    -->
    <settings>
        <setting name="logImpl" value="LOG4J"/>
    </settings>

【4】结果

 5、建造者设计模式介绍

又称生成器模式 ,
是一种对象的创建模式。 可以将一个产品的内部表象与产品的生成过程分割开来 , 从而可以使一个建造过程生成具有 不同的内部表象的产品 ( 将一个复杂对象的构建与它的表示分离 , 使得同样的构建过程可以创建不同的表示 ).。
这样用户只需指定需要建造的类型就可 以得到具体产品 , 而不需要了解具体的建造过程和细节
在建造者模式中 , 角色分指导者 (Director) 与建造者 (Builder): 用户联系指导者 , 指导者指挥建造者 , 最后得到产品 . 建造者模式可以强制实行一种分步骤进行的建造过程 .

6、#{} ${}的区别

【1】#{}

表示一个 占位 ,通知 Mybatis 使用实际的参数值代替。并使用 PrepareStatement 对象执行 sql 语句 , #{…} 代替 sql 语句的 “?”
这个是 Mybatis 中的首选做法

【2】${}

表示字符串原样替换 ,通知 Mybatis 使用 $ 包含的 字符串 替换所在位置。使用 Statement 或者 PreparedStatement sql 语句和 ${} 的内容连接起来。
一般用在替换表名, 列名,不同列排序等操作。

7、动态SQL

动态 SQL MyBatis 的强大特性之一。

更新

<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>

8、分页

【1】pom.xml

<dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.2.0</version>
        </dependency>

【2】mybatis.xml

<!--分页-->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
        <!--<property name="reasonable" value="true"/>-->
    </plugins>

【3】测试

public void test5() {
        // PageHelper.startPage 必须紧邻查询语句,而且只对第一条查询语句生效
        PageHelper.startPage(2, 5);
        List<Team> teams = teamMapper.queryAll();//查询语句结尾不能有分号
        teams.forEach(team -> System.out.println(team));
        PageInfo<Team> info = new PageInfo<>(teams);
        System.out.println("分页信息如下:");
        System.out.println("当前页:" + info.getPageNum());
        System.out.println("总页数:" + info.getPages());
        System.out.println("前一页:" + info.getPrePage());
        System.out.println("后一页:" + info.getNextPage());
        System.out.println("navigatepageNums:" + info.getNavigatepageNums());
        for (int num : info.getNavigatepageNums()) {
            System.out.println(num);
        }

9、Mybatis缓存

缓存是一般的 ORM 框架都会提供的功能,目的就是提升查询的效率和减少数据库的压力。将经常查询的数据存在缓存(内存)中,用户查询该数据的时候不需要从磁盘(关系型
数据库文件)上查询,而是直接从缓存中查询,提高查询效率,解决高并发问题。
MyBatis 也有一级缓存和二级缓存,
并且预留了集成第三方缓存的接口。

【1】 一级缓存

自动开启 ,SqlSession 级别的缓存
一级缓存的作用域是同一个 SqlSession ,在同一个 sqlSession 中两次执行相同的 sql 语句,
第一次执行完毕会将数据库中查询的数据写到缓存(内存),
第二次会从缓存中获取数 据将不再从数据库查询,从而提高查询效率。

【2】二级缓存

Mapper 级别的缓存
二级缓存是多个 SqlSession 共享的,其作用域是 mapper 的同一个

【3】清空缓存的方式

1 session.clearCache( ) ;
2 execute update( 增删改 ) ;
3 session.close( );
4 xml 配置 flushCache="true"
5 rollback
6 commit

后续还有补充,有点难,先停一下

  • 3
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

初尘屿风

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值