mybatis学习笔记

概念

mapper文件:是数据库与查询方法之间的桥梁,包含mapper接口和mapper.xml。mapper接口包含方法名称及参数,mapper.xml包含具体的SQL语句,通过namespace可以将接口与xml文件对应起来。

使用经验

配置文件

一般指mybatis-config.xml文件,该文件配置数据库连接信息、缓存设置信息、mapper信息等。示例如下:

<?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.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/imooc?seUnicode=true&amp;serverTimezone=Asia/Shanghai&amp;characterEncoding=utf8&amp;autoReconnect=true&amp;useSSL=false&amp;allowMultiQueries=true"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper class="com.imooc.mybatis.mapper.UserMapper"></mapper>
    </mappers>
</configuration>

configuration中的内容才是需要自定义的。在springboot项目中,这些配置信息写在application.properties中,或者yml中,不需要以xml的形式了。如下:

server.port=28089
spring.thymeleaf.cache=false
spring.datasource.name=newbee-mall-datasource
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/newbee_mall_db?useUnicode=true&serverTimezone=Asia/Shanghai&characterEncoding=utf8&autoReconnect=true&useSSL=false&allowMultiQueries=true
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.maximum-pool-size=15
spring.datasource.hikari.auto-commit=true
spring.datasource.hikari.idle-timeout=10000
spring.datasource.hikari.pool-name=hikariCP
spring.datasource.hikari.max-lifetime=30000
spring.datasource.hikari.connection-timeout=30000
spring.datasource.hikari.connection-test-query=SELECT 1
# mybatis config
mybatis.mapper-locations=classpath:mapper/*Mapper.xml

mapper.xml

xml文件包含具体的SQL语句,接受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">
<mapper namespace="ltd.newbee.mall.dao.AdminUserMapper">

  <resultMap id="BaseResultMap" type="ltd.newbee.mall.entity.AdminUser">
    <id column="admin_user_id" jdbcType="INTEGER" property="adminUserId" />
    <result column="login_user_name" jdbcType="VARCHAR" property="loginUserName" />
    <result column="login_password" jdbcType="VARCHAR" property="loginPassword" />
    <result column="nick_name" jdbcType="VARCHAR" property="nickName" />
    <result column="locked" jdbcType="TINYINT" property="locked" />
  </resultMap>
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select
    <include refid="Base_Column_List" />
    from tb_newbee_mall_admin_user
    where admin_user_id = #{adminUserId,jdbcType=INTEGER}
  </select>

内部主要参数解释如下:

参数名含义及作用
namespace映射mapper接口,需要类全限定名称
id

与接口中的方法名称对应

parameterType填入 接口中方法参数的类型,可以是基本型,也可以是包装型,也可以是实体pojo类
resultType填入 返回结果的类型,基本型或者包装型。实体型时需要采用resultMap
resultMap将数据库数据映射为 Java 对象,如驼峰和下划线变量的不对应问题。这里就提供了相应的映射方法。column中是数据表中的字段,properties中是实体类中的方法,
#{id}预编译,避免SQL问题。

多参数SELECT及resultMap的使用

上述例子中,parameterType为单一参数,resultType也是基本参数。讨论多参数和Java对象的情况。

在mapper接口中,对于传递的多参数,可采用@Param注解。对于Java对象,直接引入类全限定名称即可。Java实体类必须有getter和setter方法。

user selectUserByNameAndAge(@Param("name") String name , @Param("age") Integer age);
    <select id="selectUserByNameAndAge" resultType="com.imooc.mybatis.model.user">
        SELECT * FROM imooc_user WHERE name = #{name} AND age = #{age}
    </select>

上面这个例子中,返回类型为user对象,mybatis会自动对结果进行映射,即数据表字段与Java字段的映射。但一般情况下,还会构建resultMap进行映射,如下所示。

    <resultMap id="baseMap" type="com.imooc.mybatis.model.user">
        <id property="id" column="id"></id>
        <result property="name" jdbcType="VARCHAR" column="name"></result>
        <result property="age" jdbcType="INTEGER" column="age"></result>
        <result property="score" jdbcType="INTEGER" column="score"></result>
    </resultMap>

    <sql id="baseSql">
        SELECT id,name,score,age FROM imooc_user
    </sql>
    <select id="selectUserByIdAndAge" resultMap="baseMap">
        <include refid="baseSql"/>
            WHERE id = #{id} AND age = #{age}
    </select>

INSERT

insert较为简单,学习插入user,以及返回主键ID的方法。insert无需resultType标签。

普通插入:

    <insert id="insertUser" parameterType="com.imooc.mybatis.model.user">
        INSERT INTO imooc_user(name,score,age) VALUES(#{name},#{score},#{age})
    </insert>

返回主键ID 插入的两种方法:(未成功)

    <insert id="insertUserReturnId" useGeneratedKeys="true" keyProperty="id" parameterType="com.imooc.mybatis.model.user">
        INSERT INTO imooc_user(name,score,age) VALUES (#{name},#{score},#{age})
    </insert>

    <insert id="insertUserSelectReturnId" parameterType="com.imooc.mybatis.model.user">
        INSERT INTO imooc_useer(name,age,score) VALUES (#{name},#{age},#{score})
        <selectKey keyColumn="id" resultType="Integer" keyProperty="id" order="AFTER">
            SELECT LAST_INSERT_ID()
        </selectKey>
    </insert>

UPDATE和DELETE

较为简单,与INSERT类似。后续作为练习。

OGNL语句和IF标签的简单使用

注意,使用可选查询条件时,传入的参数应该是user的Java对象,如果是属性,那么不能选择查询的参数种类。

    <select id="selectByIf" resultMap="baseMap" parameterType="com.imooc.mybatis.model.user">
        <include refid="baseSql"></include> WHERE id = #{id}
         <if test=" name != null">
             AND name = #{name}
         </if>
        <if test=" age != null">
            AND age = #{age}
        </if>
    </select>

查询后,通过动态代理生成的SQL语句为:SELECT id,name,score,age FROM imooc_user WHERE id = ? 

choose-when-otherwise标签

Choose标签可以看作Java中的switch语句,default相当于otherwise,遇到true时,直接执行并结束。通过条件判断,执行不同的语句。

    <select id="selectUserBychoose" resultMap="baseMap" parameterType="com.imooc.mybatis.model.user">
        <include refid="baseSql"></include> WHERE
         <choose>
             <when test="id != null and id != ''">id = #{id}</when>
             <when test="name != null">name = #{name}</when>
         </choose>
    </select>

业务逻辑:先按照id查询,若id为空再按照name查询。

where、set、trim标签

本质上来说,这三个标签都是服务于SELECT  INSERT UPDATE语句的,为了从逻辑上,以及从语法上拼接出正确的SQL语句。

其中,where标签与SQL里的WHERE没什么区别,可配合IF使用;set标签中必须含有一个执行的语句;trim标签主要是用来增减字符串的,因为SQL语句会增减括号,逗号等。它包含四个参数:

标签含义
prefix一般与IF配合,对于每个判断若不为空,增加相应字符
prefixOverrides剔除多余前缀字符
suffix与prefix类似
suffixOverrides提出多余后缀字符

for-each标签

一般来说,使用批量操作的数据结构一般是List、array、map,最常用的是List。该标签的重点是xml文件的表示,引入一个SELECT例子:

    <select id="selectUserByIdAndForeach" resultType="com.imooc.mybatis.model.user">
        <include refid="baseSql"></include> WHERE id IN
         <foreach collection="ids" open="(" close=")" separator="," item="item" index="index">
             #{item}
         </foreach>
    </select>

有6个重要的标签,本质上还是对语句进行拆分解析,生成合适的SQL语句。功能及作用如下所示:

标签含义
collection表示需要遍历的集合,与接口参数类型一致。若无@Param,则为list或array或map
item集合中的单个元素,可用item表示。可以在item上进行操作。
open、close分别表示原集合中开始遍历的起点和终点。这里的左括号和右括号分别表示list的左右括号
seperator集合中,各元素之间的分割,一般是逗号
index表示序列

进一步,给出批量插入的例子:

<insert id="insertUsers">
  INSERT INTO imooc_user(username,age,score)
  VALUES
  <foreach collection="users" item="user" separator=",">
    (#{user.username}, #{user.age}, #{user.score})
  </foreach>
</insert>

联表查询

(65条消息) Mybatis-多表联查_mybatis多表联合查询_糊涂涂是个小盆友的博客-CSDN博客

一对一联表查询

associate,关键标签:properties、javaType。

<?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.jt.mapper.EmpMapper">

    <!-- 一对一关联查询 -->
    <select id="findAll" resultMap="empRM">
        select e.emp_id,e.emp_name,
               d.dept_id,d.dept_name
	    from emp e,dept d
	    where e.dept_id = d.dept_id
    </select>

    <!--3.完成一对一封装
        固定用法:
            1.association: 将结果集封装为单独的对象 dept
            2.property 需要封装的属性名称
            3.javaType 固定写法: 属性的类型
    -->
    <resultMap id="empRM" type="Emp">
        <!--1.主键字段 -->
        <id property="empId" column="emp_id"></id>
        <!--2.映射其它属性字段-->
        <result property="empName" column="emp_name"></result>
        <association property="dept" javaType="Dept">
            <!--3.完成dept对象的封装-->
            <id property="deptId" column="dept_id"/>
            <result property="deptName" column="dept_name"/>
        </association>
    </resultMap>

</mapper>

一对多联表查询

collection,关键标签:properties、ofType。

子查询就可以通过一对多联表查询来实现。

<?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.jt.mapper.DeptMapper">
    
    <select id="findAll" resultMap="deptRM">
        select d.dept_id,d.dept_name,e.emp_id,e.emp_name
	from dept d,emp e
	where e.dept_id = d.dept_id
    </select>

    <!--Mybatis的映射,一般都是一级封装 -->
    <resultMap id="deptRM" type="Dept">
        <!--指定主键-->
        <id column="dept_id" property="deptId"/>
        <!--封装其它的属性字段-->
        <result column="dept_name" property="deptName"/>
        <!--封装集合 属于同一个部门下的员工,封装到一个集合中 -->
        <collection property="emps" ofType="Emp">
            <id column="emp_id" property="empId"/>
            <result column="emp_name" property="empName"/>
        </collection>
    </resultMap>
</mapper>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值