mybatis学习

目录

CRUD

1. namespace

2. select

3. insert

4. update

5. delete

配置解析

 核心配置文件

环境配置(environments)

 属性(properties)

类型别名(typeAliases)

设置

其他配置

映射器(mappers)

生命周期和作用域

SqlSessionFactoryBuilder:

SqlSessionFactory:

SqlSession:

多对一处理,一对多处理

动态SQL

IF

choose (when, otherwise)

trim (where, set)

Foreach

SQL片段

其他


mybatis官网:MyBatis中文网

狂神笔记:【狂神说】Mybatis学习笔记(全)_狂神说mybatis课件笔记-优快云博客


CRUD

1. namespace

namespace 是 MyBatis 映射文件(.xml)中的一个重要属性,它为映射文件中的 SQL 语句提供了一个命名空间,主要作用是避免不同映射文件中 SQL 语句的 ID 冲突,同时也方便在 Java 代码中定位对应的 SQL 语句。通常,namespace 的值会设置为对应的 Mapper 接口的全限定名。

<mapper namespace="com.example.dao.UserMapper">
    <!-- 这里可以定义具体的SQL语句 -->
</mapper>

2. select

select 标签用于从数据库中查询数据。可以通过设置不同的属性来指定查询的条件、返回结果的类型等。

<mapper namespace="com.example.dao.UserMapper">
    <select id="getUserById" parameterType="int" resultType="com.example.entity.User">
        SELECT * FROM users WHERE id = #{id}
    </select>
</mapper>
  • id:唯一标识该 SQL 语句,在 Java 代码中调用时会用到。
  • parameterType:指定传入参数的类型。
  • resultType:指定查询结果的映射类型。

3. insert

insert 标签用于向数据库中插入数据。可以通过设置 parameterType 来指定传入参数的类型,同时可以使用 useGeneratedKeys 和 keyProperty 属性来获取插入记录的自增主键。

<mapper namespace="com.example.dao.UserMapper">
    <insert id="insertUser" parameterType="com.example.entity.User" useGeneratedKeys="true" keyProperty="id">
        INSERT INTO users (name, age) VALUES (#{name}, #{age})
    </insert>
</mapper>
  • useGeneratedKeys:设置为 true 表示使用数据库的自增主键。
  • keyProperty:指定将自增主键值映射到 Java 对象的哪个属性上。

4. update

update 标签用于更新数据库中的数据。同样需要指定传入参数的类型和更新的 SQL 语句。

<mapper namespace="com.example.dao.UserMapper">
    <update id="updateUser" parameterType="com.example.entity.User">
        UPDATE users
        SET name = #{name}, age = #{age}
        WHERE id = #{id}
    </update>
</mapper>

5. delete

delete 标签用于从数据库中删除数据。需要指定传入参数的类型和删除的条件。

<mapper namespace="com.example.dao.UserMapper">
    <delete id="deleteUser" parameterType="int">
        DELETE FROM users WHERE id = #{id}
    </delete>
</mapper>


配置解析

配置_MyBatis中文网


 核心配置文件

mybatis-config.xml
MyBatis的配置文件包含了会深深影响MyBatis行为的设置和属性信息。

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

环境配置(environments)

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


 属性(properties)

我们可以通过properties属性来实现引用配置文件
这些属性都是可外部配置且可动态替换的,既可以在典型的Java属性文件中配置,亦可通过properties元素的子元素来传递。【db.properties】
编写一个配置文件
db.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8
username=root
password=123456

在核心配置文件中映入

    <!--引入外部配置文件-->
    <properties resource="db.properties">
        <property name="username" value="root"/>
        <property name="pwd" value="123123"/>
    </properties>
  • 可以直接引入外部文件
  • 可以在其中增加一些属性配置
  • 如果两个文件有同一个字段,优先使用外部配置文件的!

类型别名(typeAliases)

  • 类型别名是为Java类型设置一个短的名字。
  • 存在的意义仅在于用来减少类完全限定名的冗余。
    <!--可以给实体类起别名-->
    <typeAliases>
        <typeAlias type="com.kuang.pojo.User" alias="User" />
    </typeAliases>

也可以指定一个包名,MyBatis会在包名下面搜索需要的JavaBean,比如:
扫描实体类的包,它的默认别名就为这个类的类名,首字母小写!

    <!--可以给实体类起别名-->
    <typeAliases>
        <package name="com.kuang.pojo"/>
    </typeAliases>

在实体类比较少的时候,使用第一种方式。
如果实体类十分多,建议使用第二种。
第一种可以DIY别名,第二种则不行,如果非要改,需要在实体上增加注解

@Alias("user")
//实体类
public class User {}

设置

这是MyBatis中极为重要的调整设置,它们会改变MyBatis的运行时行为。

其他配置

  • typeHandlers(类型处理器)
  • objectFactory(对象工厂)
  • plugins(插件)
    1. mybatis-generator-core
    2. mybatis-plus
    3. 通用mapper

映射器(mappers)

MapperRegistry:注册绑定我们的Mapper文件;
方式一:【推荐使用】

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

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

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

注意点:

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

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

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

注意点:

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

生命周期和作用域

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

SqlSessionFactoryBuilder:

  • 一旦创建了 SqlSessionFactory,就不再需要它了。
  • 局部变量


SqlSessionFactory:

  • 说白就是可以想象为:数据库连接池。
  • SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例
  • SqlSessionFactory 的最佳作用域是应用作用域。
  • 最简单的就是使用单例模式或者静态单例模式。


SqlSession:

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

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


5.2 resultMap


6、日志(2020-10-24)
6.1 日志工厂
6.2 Log4j


多对一处理,一对多处理

  1. 关联-association【多对一】
  2. 集合-collection【一对多】
  3. javaType & ofType
    1. javaType 用来指定实体类中属性的类型
    2. ofType 用来指定映射到List或者集合中的pojo类型,泛型中的约束类型!
  • 多个学生,对应一个老师
  • 对于学生而言,关联–多个学生,关联一个老师【多对一】
  • 对于老师而言,集合–一个老师,有很多个学生【一对多】

多对一:

    <!--按照结果嵌套处理    -->
    <select id="getStudent2" resultMap="StudentTeacher2">
        select s.id sid,s.name sname,t.name tname
        from mybatis.student s,mybatis.teacher t
        where s.tid = t.id
    </select>    <resultMap id="StudentTeacher2" type="Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <association property="teacher" javaType="Teacher">
            <result property="name" column="tname"/>
        </association>
    </resultMap>
按照查询嵌套处理
    <!--
      思路:
          1.查询所有的学生信息
          2.根据查询出来的学生的tid,寻找对应的老师! 子查询-->
    <select id="getStudent" resultMap="StudentTeacher">
        select * from mybatis.student
    </select>

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

    <select id="getTeacher" resultType="Teacher">
        select * from mybatis.teacher where id = #{id}
    </select>

一对多:

@Data
public class Student {
    private int id;
    private String name;
    private int tid;

}

@Data
public class Teacher {
    private int id;
    private String name;

    //一个老师拥有多个学生
    private List<Student> students;
}

按照结果嵌套处理
    <!--    按结果嵌套查询-->
    <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="Teacher">
        <result property="id" column="tid"/>
        <result property="name" column="tname"/>
        <!--  复杂的属性,我们需要单独处理 对象:association 集合:collection
             javaType="" 指定属性的类型!
             集合中的泛型信息,我们使用ofType获取
             -->
        <collection property="students" ofType="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 mybatis.teacher where id = #{tid}
    </select>

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

    <select id="getStudentByTeacherId" resultType="Student">
        select * from  mybatis.student where tid = #{tid}
    </select>



动态SQL

IF

<if> 标签用于根据条件判断是否包含某一部分 SQL 语句。

 <select id="queryBlogIF" parameterType="map" resultType="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>

where

<where> 标签会自动处理 SQL 语句开头的 AND 或 OR,避免多余的条件连接词。

<select id="selectUsers" parameterType="com.example.domain.User" resultType="com.example.domain.User">
    SELECT * FROM user
    <where>
        <if test="username != null and username != ''">
            username = #{username}
        </if>
        <if test="password != null and password != ''">
            and password = #{password}
        </if>
    </where>
</select>


choose (when, otherwise)

<choose> 类似于 Java 中的 switch 语句,<when> 是条件分支,<otherwise> 是默认分支。

<select id="queryBlogChoose" parameterType="map" resultType="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>

set

在执行 update 操作时,我们往往需要根据具体情况更新部分字段,而不是所有字段。<set> 标签可以帮助我们根据传入的参数动态地生成 SET 子句,并且会自动去掉最后一个字段后面多余的逗号。

  • <set> 标签包裹了多个 <if> 标签,每个 <if> 标签根据条件判断是否需要更新相应的字段。
  • 当某个字段对应的条件满足时,会生成对应的更新语句,并在字段后面添加逗号(,)。
  • <set> 标签会自动去掉最后一个字段后面多余的逗号,确保生成的 SET 子句语法正确。

<mapper namespace="com.example.mapper.UserMapper">
    <!-- 更新用户信息的方法 -->
    <update id="updateUser" parameterType="com.example.domain.User">
        UPDATE user
        <set>
            <!-- 如果 username 不为空,则更新 username 字段 -->
            <if test="username != null and username != ''">
                username = #{username},
            </if>
            <!-- 如果 password 不为空,则更新 password 字段 -->
            <if test="password != null and password != ''">
                password = #{password},
            </if>
            <!-- 如果 email 不为空,则更新 email 字段 -->
            <if test="email != null and email != ''">
                email = #{email},
            </if>
        </set>
        WHERE id = #{id}
    </update>
</mapper>


trim 

<trim> 标签可以去除 SQL 语句中的多余字符,如前缀、后缀、指定字符等。

这里的 <trim> 标签会在 SQL 语句前添加 WHERE 关键字,并去除开头多余的 AND 或 OR,同时去除结尾多余的 AND 或 OR

<select id="selectUsers" parameterType="com.example.domain.User" resultType="com.example.domain.User">
    SELECT * FROM user
    <trim prefix="WHERE" prefixOverrides="AND |OR" suffixOverrides="AND |OR">
        <if test="username != null and username != ''">
            AND username = #{username}
        </if>
        <if test="password != null and password != ''">
            AND password = #{password}
        </if>
    </trim>
</select>

Foreach


动态 SQL 的另一个常见使用场景是对集合进行遍历(尤其是在构建 IN 条件语句的时候)。

foreach 元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。它也允许你指定开头与结尾的字符串以及集合项迭代之间的分隔符。这个元素也不会错误地添加多余的分隔符,看它多智能!

提示你可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象作为集合参数传递给 foreach。当使用可迭代对象或者数组时,index 是当前迭代的序号,item 的值是本次迭代获取到的元素。当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。

<!--select * from blog where 1=1 and (id=1 or id=2 or id=3)
        我们现在传递一个万能的map,这map中可以存在一个集合!
        -->
    <select id="queryBlogForeach" parameterType="map" resultType="Blog">
        select * from mybatis.blog
        <where>
            <foreach collection="ids" item="id" open="and (" close=")" separator="or">
                id = #{id}
            </foreach>
        </where>
    </select>

SQL片段


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

使用SQL标签抽取公共的部分

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

在需要使用的地方使用Include标签引用即可

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

其他

Mybatis缓存

日志

注解开发

分页

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值