Mybatis

Mybatis

环境

  • JDk1.8
  • Mysql 5.7
  • maven 3.6.1
  • IDEA

回顾

  • JDBC
  • Mysql
  • java基础
  • Maven
  • Junit

SSM框架

配置文件,看官网文档

1、简介

1.1 什么是Mybatis

img

  • MyBatis 是一款优秀的持久层框架

  • 它支持自定义 SQL、存储过程以及高级映射。

  • MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

1.2 如何获得Mybatis

  • maven仓库:

    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.3</version>
    </dependency>
    
    
  • Github: https://github.com/mybatis/mybatis-3/releases

  • 中文文档:https://github.com/tuguangquan/mybatis

持久层

数据持久化

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

目的:帮助程序员将数据存到数据库中

2、第一个Mybatis程序

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

2.1 搭建环境

新建项目

  1. 新建一个普通Maven项目
  2. 删除src目录
  3. 导入Maven依赖
 <dependencies>
    <!--mysql驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.49</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
<!--        junit   -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

2.2 创建一个模块

  • 编写mybatis的核心配置文件
<?xml version="1.0" encoding="UTF8" ?>
<!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?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="wrz485251mysql"/>
            </dataSource>
        </environment>

    </environments>

</configuration>
  • 编写mybatis工具类
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();
        }

    }

    public static SqlSession getSqlSession(){
       return sqlSessionFactory.openSession();

    }

}

2.3、编写代码

  • 实体类
public class User {
    private int id;
    private String userName;
    private int userPassword;
    private int phone;

    public User() {

    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public int getUserPassword() {
        return userPassword;
    }

    public void setUserPassword(int userPassword) {
        this.userPassword = userPassword;
    }

    public int getPhone() {
        return phone;
    }

    public void setPhone(int phone) {
        this.phone = phone;
    }

    public User(int id, String userName, int userPassword, int phone){
        this.id=id;
        this.userName=userName;
        this.userPassword=userPassword;
        this.phone= phone;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", userPassword=" + userPassword +
                ", phone=" + phone +
                '}';
    }
    
}
  • Dao接口
public interface UserDao {
    List<User> getUserList();
}
  • 接口实现类由原来的UserDaoImpl转变为一个Mapper配置文件
<?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=绑定一个对应的Dao/Mapper接口-->
<mapper namespace="com.guo.dao.UserDao">
   <select id="getUserList" resultType="com.guo.pojo.User" >
       select * from smbms.smbms_user
   </select>
</mapper>

2.4、测试

  • junit 测试
 @Test
    public void test(){
//        第一步:获得SqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
//        方式一:getMapper
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        List<User> userList = userDao.getUserList();

        for(User user:userList){
            System.out.println(user);
        }

//        关闭SqlSession
        sqlSession.close();
    }

3、CEUD

3.1 namespace

namespace种的包名要和Dao/mapper接口的包名一致!

3.2 select

选择,查询语句:

  • id: 就是对应的namespace中的方法名;
  • resultType: Sql语句执行的返回值!
  • parameterType: 参数类型!
  1. 编写接口
 User getUserById(int id);
  1. 编写对应的mapper中的sql语句
<select id="getUserById" resultType="com.guo.pojo.User" parameterType="int" >
       select * from smbms.smbms_user where id = #{id}
</select>
  1. 测试
 @Test
    public void getUserById(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.getUserById(1);
        System.out.println(user);
        sqlSession.close();
    }

3.3 insert

<insert id="addUser" parameterType="com.guo.pojo.User">
        insert into smbms.smbms_user (id,userName,userPassword) values (#{id},#{userName},#{userPassword});
</insert>

*** 注意点:增删改需要提交事务! ***

3.4 万能Map

假如实体类或者数据库的表,字段或者参数过多,应该考虑使用Map!

int addUser2(Map<String,Object> map);
<!--    对象中的属性,可以直接取出来传递map的key     -->
<insert id="addUser" parameterType="map">
        insert into smbms.smbms_user (id,userName,userPassword) values (#{userid },#{userName},#{userPassword});
</insert>
    @Test
    public void addUser2(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        HashMap<String, Object> map = new HashMap<>();
        map.put("userid",5);
        map.put("userName","Hello");
        map.put("userPassword","2333344");
        mapper.addUser2(map);
        sqlSession.close();
    }

3.5 模糊查询怎么写

  1. java代码执行的时候,传递通配符%%
List<User> userList = mapper.getUserLike("%李%");
  1. 在sql拼接中使用通配符!

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

4、 配置解析

4.1 核心配置文件

  • mybatis-config,xml

  • MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息。 配置文档的顶层结构如下:

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

4.2 环境配置

  • myBatis可以配置成适应多种环境
  • 尽管可以配置多种环境。但每个SqlSessionFactory实例只能选择一种环境
  • 学会使用配置多套运行环境
  • myBatis默认的事务管理器就是JDBC,连接池:POOLED

4.3 属性

  • 这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 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=wrz485251mysql
    

    在核心配置文件中引入

     <!--    引入外部配置文件    -->
        <properties resource="db.properties"/>
    
  • 可以直接引入外部文件

  • 可以在其中增加一些配置属性

  • 如果两个文件有同一字段,优先使用外部配置文件!

4.4 类型别名

  • 类型别名是为Java类型设置一个短的名字
  • 存在的意义仅用来减少完全限定名的冗余
 <!--    别名      -->
    <typeAliases>
        <typeAlias type="com.guo.pojo.User" alias="User"/>
    </typeAliases>
  • 也可以指定一个包名,MyBatis会在包名下搜索需要的javaBean,比如:扫描实体类的包,默认为这个类的类名,首字母小写!

      <!--    别名      -->
        <typeAliases>
            <package name="com.guo.pojo"/>
        </typeAliases>
    

4.5 映射器

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

  • 方式一:

    !--    每一个Mapper.XML都需要在Mybatis核心配置文件中注册   -->
        <mappers>
           <mapper resource="com/guo/dao/UserMapper.xml"/>
          
        </mappers>
    
  • 方式二:使用class文件绑定注册

    <mappers>
    <!--        <mapper resource="com/guo/dao/UserMapper.xml"/>-->
            <mapper class="com.guo.dao.UserMapper"/>
        </mappers>
    
    注意点:
    • 接口和配置文件必须同名!
    • 接口和配置文件必须在同一个包下!
  • 方式三:使用扫描包进行注入绑定

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

4.6 生命周期和作用域

理解我们之前讨论过的不同作用域和生命周期类别是至关重要的,因为错误的使用会导致非常严重的并发问题

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-B2XdwG7P-1604627850784)(C:\Users\wrz__\AppData\Roaming\Typora\typora-user-images\image-20201027164505860.png)]

生命周期

SqlSessionFactoryBuilder:
  • 一旦创建了 SqlSessionFactory,就不再需要它了
  • 局部变量
SqlSessionFactory:
  • 可以想象为数据库连接池
  • SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例。
  • 最简单的就是使用单例模式或者静态单例模式。
SqlSession:
  • 连接到连接池的一个请求!
  • SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。
  • 用完之后赶紧关闭,否则资源被占用

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5MtEAVKw-1604627850786)([外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IqMRu4Di-1604627947315)(C:%5CUsers%5Cwrz__%5CAppData%5CRoaming%5CTypora%5Ctypora-user-images%5Cimage-20201027165741015.png#pic_center)]
)]

这里面的每一个Mapper,就代表一个具体的业务!

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

5.1 结果集映射

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-uhhQ1knx-1604627850789)(C:\Users\wrz__\AppData\Roaming\Typora\typora-user-images\image-20201027191432644.png)]

  • resultMap 元素是 MyBatis 中最重要最强大的元素
  • ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。

6、日志

6.1 日志工厂

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-v3bpMnWw-1604627850790)(C:\Users\wrz__\AppData\Roaming\Typora\typora-user-images\image-20201027193739158.png)]

在Mybatis中具体使用哪一个日志实现,在设置中设定!

STDOUT_LOGGING标准日志输出

在mybatis核心配置文件中,配置我们的日志!

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-RxMAnKSe-1604627850791)(C:\Users\wrz__\AppData\Roaming\Typora\typora-user-images\image-20201027194800716.png)]

6.2、Log4j

6.2.1 什么是Log4j
  • Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件
  • 我们也可以控制每一条日志的输出格式
  • 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程
  • 通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。
6.2.2 设置相关依赖
 <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
  </dependency>
6.2.3 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/kuang.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】【%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
6.2.4 配置log4j为日志的实现
 <settings>
<!--        <setting name="logImpl" value="STDOUT_LOGGING"/>-->
        <setting name="logImpl" value="LOG4J"/>
 </settings>
6.2.5 Log4j的使用

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-DNBZyUdG-1604627850792)(C:\Users\wrz__\AppData\Roaming\Typora\typora-user-images\image-20201027201941871.png)]

6.2.5 简单使用

  1. 导入相关包

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

    static Logger logger = Logger.getLogger(UserMapper.class);
    
  3. 日志级别

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-412vOAyJ-1604627850793)(C:\Users\wrz__\AppData\Roaming\Typora\typora-user-images\image-20201027203516113.png)]

7、分页

目的:减少数据的处理量

7.1 使用Limit分页

语法:SELECT * from user limit startIndex,pageSize;
SELECT * from user limit 3;	#[0,n]

使用Mybatis实现分页,核心SQL

  1. 接口

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

     <!-- 分页   -->
        <select id="getUserByLimit" parameterType="map" resultType="user">
            select * from smbms.smbms_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<>();
            map.put("startIndex",1);
            map.put("pageSize",2);
            List<User> userList = mapper.getUserByLimit(map);
            for(User user:userList){
                System.out.println(user);
            }
            sqlSession.close();
        }
    

    8、使用注解

    8.1 使用注解开发

    1. 注解在接口实现

      @Select("select * from user")
          List<User> getUsers();
      
    2. 需要在核心配置文件中绑定接口!

      	<!--    绑定接口        -->
          <mappers>
              <mapper class="com.guo.dao.UserMapper"/>
          </mappers>
      

      本质:反射机制实现

      底层:动态代理!

    8.2 CRUD

    我们可以在工具类创建的时候实现自动提交事务!

    编写接口,增加注释

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-q8wiNG89-1604627850794)(C:\Users\wrz__\AppData\Roaming\Typora\typora-user-images\image-20201028110844503.png)]

测试类:注意我们必须要将接口注册绑定到我们的核心配置文件中!

关于@Param()注解

  • 基本类型的参数或者String类型,需要加上
  • 引用类型不需要加
  • 在Sql中引用的就是在@Param中设定的属性名!

9、Lombok(等研三找工作时在用)

  1. 在IDEA中安装Lombok插件
  2. 在项目中导入相关jar包
  3. [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OxFHvUp6-1604627850794)(C:\Users\wrz__\AppData\Roaming\Typora\typora-user-images\image-20201028113006765.png)]

@Data: 无参构造,get, set, tostring, hashcode, equals

10、多对一处理

多对一:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-uHIFS3AV-1604627850795)(C:\Users\wrz__\AppData\Roaming\Typora\typora-user-images\image-20201028125220335.png)]

  • 多个学生,对应一个老师
  • 对于学生而言,多个学生关联一个老师【多对一】
  • 对于老师而言,集合,一个老师,有很多学生【一对多】

10.1 测试环境搭建

  1. 导入lombok
  2. 新建实体类Teacher,Student
  3. 建立Mapper接口
  4. 建立Mapper.xml文件
  5. 在核心配置文件中绑定注册我们的Mapper接口或者文件!
  6. 测试查询是否成功!

10.2 按照查询嵌套处理

<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">


<mapper namespace="com.guo.dao.StudentMapper">
    <select id="getStudent" resultMap="StudentTeacher">
        select * from student
    </select>

    <resultMap id="StudentTeacher" type="com.guo.pojo.Student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <!--    复杂的属性,我们需要单独处理
                对象:association
                集合:collection
        -->
        <association property="teacher" column="tid" javaType="com.guo.pojo.Teacher" select="getTeacher"/>
    </resultMap>

    <select id="getTeacher" resultType="com.guo.pojo.Teacher">
        select * from teacher where id = #{id}
    </select>
</mapper>

10.3 按照结果嵌套处理

 <!-- 按照结果嵌套查询处理  -->
    <select id="getStudent2" resultMap="StudentTeacher2">
        select student.id sid,student.name sname,teacher.name tname
        from student,teacher
        where student.id = teacher.id;
    </select>

    <resultMap id="StudentTeacher2" type="com.guo.pojo.Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <association property="teacher" javaType="com.guo.pojo.Teacher">
            <result property="name" column="tname"/>
        </association>
    </resultMap>

注意:映射文件中实体类名要写全限定名

回顾Mysql多对一查询方式:

  • 子查询
  • 联表查询

11、动态SQL

11.1 IF

 <select id="queryBlogIF" parameterType="map" resultType="com.guo.pojo.Blog">
        select * from mybatis.blog where 1=1
        <if test=" title != null">
            and title = #{title}
        </if>
        <if test="author!= null">
            and author = #{author}
        </if>
 </select>

11.2 choose(when,otherwise)

<select id="queryBlogChoose" parameterType="map" resultType="com.guo.pojo.Blog">
        select * from mybatis.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>

    <update id="updateBlog" parameterType="map">
        update mybatis.blog
        <set>
            <if test="title != null">
                title = #{title},
            </if>
            <if test="author != null">
                author = #{author}
            </if>
        </set>
        where id = #{id}
    </update>

所谓的动态SQL,本质还是SQL语句,只是我们可以在SQL层面,去执行一个逻辑代码

12、缓存

12.1 简介

title = #{title} and author = #{author} and views = #{views} ```

    <update id="updateBlog" parameterType="map">
        update mybatis.blog
        <set>
            <if test="title != null">
                title = #{title},
            </if>
            <if test="author != null">
                author = #{author}
            </if>
        </set>
        where id = #{id}
    </update>

所谓的动态SQL,本质还是SQL语句,只是我们可以在SQL层面,去执行一个逻辑代码

12、缓存

12.1 简介

  • 存放在内存的临时数据
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值