《springboot实战》第九章 springboot 整合MyBatis - xml、注解篇

系列文章目录

第一章 SpringBoot起步
第二章 springboot 配置文件、多环境配置、运行优先级
第三章 springboot 统一日志
第四章 SpringBoot加载静态文件资源
第五章 springboot 拦截器
第六章 实现自定义全局异常处理
第七章 springboot 数据库应用
第八章 springboot 整合Druid
第九章 springboot 整合MyBatis - xml、注解篇
第十一章 整合Mybatis plus
第十二章 SpringBoot整合swagger-bootstrap-ui



在这里插入图片描述


前言

MyBatis 是一个半自动化的 ORM 框架,所谓半自动化是指 MyBatis 只支持将数据库查出的数据映射到 POJO 实体类上,而实体到数据库的映射则需要我们自己编写 SQL 语句实现。
官网:https://mybatis.net.cn/index.html

1、添加mybatis依赖

<dependency>
   <groupId>org.mybatis.spring.boot</groupId>
   <artifactId>mybatis-spring-boot-starter</artifactId>
   <version>2.2.0</version>
</dependency>

2、定义bean

package com.xxx.springboot.entity;

/**
 * 房子信息
 */
public class HouseInfo {
    /**
     * 主键
     */
    private Integer id;

    /**
     * 名称
     */
    private String name;

    /**
     * 户型
     */
    private String type;

    /**
     * 地址
     */
    private String address;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

3、查询数据 - select

使用 Mapper 进行开发时,需要遵循以下规则:

  • mapper 映射文件中 namespace 必须与对应的 mapper 接口的完全限定名一致。
  • mapper 映射文件中 statement 的 id 必须与 mapper 接口中的方法的方法名一致
  • mapper 映射文件中 statement 的 parameterType 指定的类型必须与 mapper 接口中方法的参数类型一致。
  • mapper 映射文件中 statement 的 resultType 指定的类型必须与 mapper 接口中方法的返回值类型一致。

3.1、定义Mapper

package com.xxx.springboot.mapper;
import com.xxx.springboot.entity.HouseInfo;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
 * 房屋信息mapper类
 */
@Mapper
public interface HouseInfoMapper {
    List<HouseInfo> queryHouseInfo();
}

3.2、定义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.xxx.springboot.mapper.HouseInfoMapper">
    <!--查询列名集合-->
    <resultMap id="BaseResultMap" type="HouseInfo">
        <id column="id" jdbcType="INTEGER" property="id"/>
        <result column="name" property="name" jdbcType="VARCHAR"/>
        <result column="type" property="type" jdbcType="VARCHAR"/>
        <result column="address" property="address" jdbcType="VARCHAR"/>
    </resultMap>
    <!--定义查询方法-->
    <select id="queryHouseInfo" resultMap="BaseResultMap">
        select * from house_info
    </select>
</mapper>

3.3、动态查询语句定义

元素属性

属性描述
id在命名空间中唯一的标识符,可以被用来引用这条语句。
parameterType将会传入这条语句的参数的类全限定名或别名。这个属性是可选的,因为 MyBatis 可以通过类型处理器(TypeHandler)推断出具体传入语句的参数,默认值为未设置(unset)。
resultType期望从这条语句中返回结果的类全限定名或别名。 注意,如果返回的是集合,那应该设置为集合包含的类型,而不是集合本身的类型。 resultType 和 resultMap 之间只能同时使用一个。
resultMap对外部 resultMap 的命名引用。结果映射是 MyBatis 最强大的特性,如果你对其理解透彻,许多复杂的映射问题都能迎刃而解。 resultType 和 resultMap 之间只能同时使用一个。
flushCache将其设置为 true 后,只要语句被调用,都会导致本地缓存和二级缓存被清空,默认值:false。
useCache将其设置为 true 后,将会导致本条语句的结果被二级缓存缓存起来,默认值:对 select 元素为 true。
timeout这个设置是在抛出异常之前,驱动程序等待数据库返回请求结果的秒数。默认值为未设置(unset)(依赖数据库驱动)。
<!--定义查询方法-->
<select id="queryHouseInfo" resultMap="BaseResultMap">
    select * from house_info
    <where>
        <!--判断语句-->
        <if test="name != null and name != ''">
            and name = #{name}
        </if>
        <if test="type != null and type != ''">
            and type = #{type}
        </if>
        <if test="address != null and address != ''">
            and address like concat('%',#{address},'%')
        </if>
    </where>

</select>

3.4、配置文件

mybatis:
  #指定mapper.xml的位置
  mapper-locations: classpath:mybatis/mapper/*.xml
  #实体类的位置
  type-aliases-package: com.hqyj.springboot.entity

4、新增数据 - insert

<!--新增数据-->
<insert id="insertHouserInfo" useGeneratedKeys="true" keyProperty="id">
    insert into house_info(name,type,address) values(#{name},#{type},#{address})
</insert>
<!--批量插入-->
<insert id="batchInsertHouserInfo" useGeneratedKeys="true" keyProperty="id">
    insert into house_info(name,type,address) values
    <foreach collection="list" item="houseInfo" separator=",">
        (#{houseInfo.name},#{houseInfo.type},#{houseInfo.address})
    </foreach>
</insert>
/**
 * 新增房屋信息数据
 * @param houseInfo
 * @return
 */
public int insertHouserInfo(HouseInfo houseInfo);
/**
 * 新增房屋信息数据
 * @param listHouse
 * @return
 */
public int batchInsertHouserInfo(List<HouseInfo> listHouse);
<insert id="insertHouserInfoExt" >
    insert into house_info(name,type,address) values(#{name},#{type},#{address})
</insert>
/**
 * 新增房屋信息数据
 * @param name
 * @param type
 * @param address
 * @return
 */
public int insertHouserInfoExt(@Param("name") String name, @Param("type")String type, @Param("address")String address );

5、注解形式

在Mapper方法上加注解,废弃xml配置方式

@Select
@Mapper
public interface OrderMapper {
    /**
     * 订单查询
     * @return
     */
    @Select("SELECT\n" +
            "\ta.id,\n" +
            "\ta.orderNo\n" +
            "FROM\n" +
            "\tgoods_order a")
    @Results(id="orderMap",value = {
            @Result(column = "id",property = "id",id = true),
            @Result(column = "orderNo",property = "orderNo"),
            @Result(column = "id",property = "listOrderDetail",
            many = @Many(select = "getOrderDetailByOrderId",fetchType = FetchType.LAZY))

    })
    List<Order> queryOrder();

    @Select("select id orderDetailId,order_id orderId,good_name goodName from goods_order_detail where id = #{orderId}")
    List<OrderDetail> getOrderDetailByOrderId(@Param("orderId") Integer orderId);
}


@Update("<script>" +
        "update t_emp" +
        "    <set >" +
        "      <if test=\"empName != null\" >" +
        "        emp_name = #{empName,jdbcType=VARCHAR},\n" +
        "      </if>" +
        "      <if test=\"empTel != null\" >" +
        "        emp_tel = #{empTel,jdbcType=VARCHAR}," +
        "      </if>" +
        "      <if test=\"empEducation != null\" >" +
        "        emp_education = #{empEducation,jdbcType=VARCHAR}," +
        "      </if>" +
        "      <if test=\"empBirthday != null\" >" +
        "        emp_birthday = #{empBirthday,jdbcType=DATE}," +
        "      </if>" +
        "      <if test=\"fkDeptId != null\" >" +
        "        fk_dept_id = #{fkDeptId,jdbcType=INTEGER}," +
        "      </if>" +
        "    </set>" +
        "    where emp_id = #{empId,jdbcType=INTEGER}" +
        "</script>")
int updateByPrimaryKeySelective(Employee record);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

青花科技

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

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

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

打赏作者

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

抵扣说明:

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

余额充值