环境配置:
pom依赖:直接打mybatis、MySQL即可
yml文件配置:
此处只写mybatis的配置,datasource只写url
mybatis:
# 该配置配置的是所有的.xml文件
mapper-locations: classpath:/mybatis/*.xml
# 该配置是实体类的包路径
type-aliases-package: com.example.demoforspringboot.model
spring:
datasource:
url: jdbc:mysql://localhost:3306/hangge?serverTimezone=Asia/Shanghai
mybatis查询
查询要分析三件事:1. 要查询xxx,如何写sql语句 2. 是否需要传参数 3. 返回值是什么
书写一个查询功能的流程:
创建实体类(每个实体类都要有getset方法) 创建 .xml文件 编写标签 开启驼峰命名映射
.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">
添加标签,并添加 namespace
属性,在和SpringBoot结合使用的使用namespace的值必须是要绑定mapper接口的全限定名称,在这里是namespace="com.example.demoforspringboot.mapper.GoodsMapper"
(在不与SpringBoot结合使用的时候,该属性可看作是某个表对应的mapper名称,或者某一部分想要的特定sql功能语句集合的名称。namespace
是为了帮助我们定位到一条具体的sql语句。但是现在基本都是和SpringBoot结合使用了,所以括号的内容就当作看个乐
)
<?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.example.demoforspringboot.mapper.GoodsMapper">
</mapper>
简单查询
查询所有的商品信息
添加标签, 加上 id
resultType
属性,id是这个sql语句对应的java方法名,resultType是sql语句查询出来的结果的类型
带参数查询
ResultMap结果映射查询
ResultMap的好处就是将复杂查询的结果映射成Dto对象来保存
先来看如何构建resuleMap
需求:查询商品和其对应的分类
构建Dto对象
package com.example.demoforspringboot.dto;
import com.example.demoforspringboot.entity.Goods;
import lombok.Data;
@Data
public class GoodsDto {
private Goods goods = new Goods();
private String categoryName;
private String test;
}
在.xml文件的<mapper></mapper>
标签中添加 <resultMap></resultMap>
标签,并要写明id与type
type是要映射的实体类,要写出实体类的完整类名
id是在当前namespace下这个resultMap名字,通常用 “rm+特定的实体类名”, 这里使用rmGoods
<resultMap id="rmGoods" type="com.example.demoforspringboot.dto.GoodsDto">
</resultMap>
建立字段与实体类属性的映射,要建立主键字段和其他字段的映射。
主键字段映射的标签是<id></id>
和其他字段的标签是<result></result>
这两个标签都需要有property
column
属性,property
是实体类的属性, column
是数据表中字段的名称
<resultMap id="selectGoodsDto" type="com.example.demoforspringboot.dto.GoodsDto">
<!--设置主键字段与属性映射-->
<id property="goods.goodsId" column="goods_id"></id>
<!--设置非主键字段与属性映射-->
<result property="goods.title" column="title"></result>
<result property="goods.originalCost" column="original_cost"></result>
<result property="goods.currentPrice" column="current_price"></result>
<result property="goods.discount" column="discount"></result>
<result property="goods.isFreeDelivery" column="is_free_delivery"></result>
<result property="categoryName" column="category_name"></result>
</resultMap>
由于Dto类中有一个属性是goods对象,所以在做结果映射的时候采用goods.${Goods.property}的形式,他表示“将数据库字段goods_id映射到goods对象的goodsId属性上”
在<select></select>
中使用resultMap:
<select id="selectGoodsDto" resultMap="rmGoods">
select *, category_name from t_goods, t_category order by current_price desc limit 20
</select>
其中,id要和mapper接口中的方法名称完全一致, resultMap要和定义的resultMap的id完全一致