mybatis入门——MyBatis的基本使用

这篇博客主要是将自己之前在学习mybatis的时候在typora做的笔记放在自己的博客上,感觉就像是复习一下(也是该好好写一下博客了)
mybatis的官方文档

一、什么是mybatis

MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
这里说到的持久层,就是把持久的动作封装成一个独立的层,这是为了降低功1653能代码之间的关联。创建一个更清版晰的抽象,提高代码的内聚力,降低代码的耦合度,从而增强代码的要劳动局生和可重用性。

二、我的第一个MyBatis程序

这里使用maven项目管理来实现

1. 导入MySQL,MyBatis依赖文件

        <!-- Mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.5</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>       

2.编写配置文件mybatis-config.xml

  1. mysql环境配置
    <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/test"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
  1. 实体类构建(此处省略一些方法)
public class Student {

    private String sno;
    private String sname;
    private String sage;

}

3.mapper接口构建

public interface StudentMapper {

    public List<Student> selectStudent(@Param("sname") String sname);

}
  1. 相应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">

<!--注意这里要添加mapper接口的全限定名-->
<mapper namespace="com.achao.Mapper.StudentMapper">
    <select id="selectStudent" resultType="com.achao.pojo.Student">
    select * from test.student where sno = 5478
    <if test="sname != null">
        and sname like '%${sname}%'
    </if>
  </select>
</mapper>
  1. mybatis-config配置文件中添加上mapper配置文件的路径(默认路径是在resources路径下)
    <mappers>
        <mapper resource="StudentMapper"></mapper>
    </mappers>

注意:这里使用resources里面的时候没有加文件后缀的话会出现错误,建议加上。我有一个测试没有加后缀出现了问题,但是有一个没有加却没有问题不知道什么原因。
6. 创建一个工具类,获得SqlSession、初始化配置

public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            String resource = "mybatis-config";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static SqlSession getSession(){
        return sqlSessionFactory.openSession(true);
    }

}

这里添加配置文件的时候会出现的问题同上
7.测试代码能否运行

        SqlSession session = MybatisUtils.getSession();
        StudentMapper studentMapper = session.getMapper(StudentMapper.class);
        List<Student> students = studentMapper.selectStudent("achao");
        System.out.println(students);
        session.close();

运行成功!
其他说明:MyBatis当然还提供了不使用xml配置文件配置环境的方法,就是使用它的配置类,详情请见官方文档,这里不展示。

三、MyBatis配置文件的设置

1、根据官网的介绍,配置文件的设置(标签分为以下几类)

在这里插入图片描述
需要注意的是,在配置文件中这些标签的顺序不能改变,否则会报错
在这里一些比较容易记住的就不在这里记录了,只是简单的讲解一下它的作用就好了

2、properties(属性)

  • 通过单独的创建一个properties文件来单独地设置配置文件里面的参数
<properties resource="org/mybatis/example/config.properties">
<property name="username" value="${username:ut_user}"/>
 <property name="password" value="F2Fa3!33TYyg"/>
</properties>
  • 这种表达方式来实现当没有外部的properties文件来映射对应的属性值的时候,使用默认值ut_user

3、settings(设置)

主要是改变使用MyBatis时候的一些运行时行为。详情见官方文档的一个表格

4、typeAliases(类型别名)

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

  • 第一种方式
<typeAliases>
  <typeAlias alias="Author" type="domain.blog.Author"/>
  <typeAlias alias="Blog" type="domain.blog.Blog"/>
  <typeAlias alias="Comment" type="domain.blog.Comment"/>
  <typeAlias alias="Post" type="domain.blog.Post"/>
  <typeAlias alias="Section" type="domain.blog.Section"/>
  <typeAlias alias="Tag" type="domain.blog.Tag"/>
</typeAliases>
  • 第二种方式
    指定一个报名,在这个包下面的类使用别名
<typeAliases>
  <package name="domain.blog"/>
</typeAliases>

这个时候MyBatis会扫描这个包下的注解,使用@Aliases(name)可以将特定类设置别名为name。没有添加注解的类默认使用类名的小写作为别名使用

5、environments(环境配置)

可以设置多种配置文件环境(比如当需要连接两个数据库的时候),但是一个SqlSessionFactory实例只能选择一种环境
关键点

  • 默认使用的环境 ID(比如:default=“development”)
  • 每个 environment 元素定义的环境 ID(比如:id=“development”)
  • 事务管理器的配置(比如:type=“JDBC”)
  • 数据源的配置(比如:type=“POOLED”)

6、mapper(映射器)

作用 告诉MyBatis去哪里找SQL映射语句
实现的方式有四种:

  • 使用相对于类路径的资源引用
  • 使用完全限定资源定位符
  • 使用映射器接口实现类的完全限定类名
  • 将包内的映射器接口实现全部注册为映射器

四、XML映射文件的详解(XXXMapper.xml)

需要现在mapper标签里面设置命名空间与对应的mapper接口形成映射关系

1、select

例如

<select id="selectPerson" parameterType="int" resultType="hashmap">
  SELECT * FROM PERSON WHERE ID = #{id}
</select>

id里面的值映射着对应mapper接口中的查询函数,parameterType里面的值是mapper对应函数中参数的类型,resultType是返回结果的类型。传递的参数使用#{id}的方式拼接到sql语句中。

这里主要讲一下resultMapper的使用(与parameterMap对应):
resultMapper的类型一般的对应着一个pojo实体类,基本作用是改变使用resultType的时候需要自己检查属性与字段的一致性问题。

  • 使用sql中自带的as语句使得查询到的数据字段名与map里面的属性对应
  • 使用resulMap标签显示地使得字段与属性对应
<resultMap id="userResultMap" type="User">
  <id property="id" column="user_id" />
  <result property="username" column="user_name"/>
  <result property="password" column="hashed_password"/>
</resultMap>

除此之外,select中还有很多的属性,比如flushCache,useCache,timeout等等。

2、关联处理(多对一)

有两种方式:

  • 嵌套 Select 查询
<resultMap id="blogResult" type="Blog">
  <association property="author" column="author_id" javaType="Author" select="selectAuthor"/>
</resultMap>

<select id="selectBlog" resultMap="blogResult">
  SELECT * FROM BLOG WHERE ID = #{id}
</select>

<select id="selectAuthor" resultType="Author">
  SELECT * FROM AUTHOR WHERE ID = #{id}
</select>
  • 嵌套结果映射

3、关联处理(一对多)

有两种方式:

  • 嵌套 Select 查询
    在这里插入图片描述
  • 嵌套结果映射
    在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43967401/article/details/106448943