1.创建工程
Spring Initializr下 web里勾选Spring Web SQL里勾选Mybatis Framework和MySql Driver
2.在application.properties里面添加链接数据库的信息(如下)
spring.datasource.url=jdbc:mysql://localhost:3306/db1?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true
spring.datasource.username=root
spring.datasource.password=root
#配置Mybatis书写SQL语句的xml文件的位置
mybatis.mapper-locations=classpath:mappers/*xml
3.创建config包中MybatisConfig配置类, 通过MapperScan注解 取代每个Mapper接口类中的@Mapper注解
类上两个注解 @Configration 和@MapperScan("写mapper接口的包路径")
4.创建实体类 和mapper接口 例如entity.Product和mapper.ProductMapper
扩展--pojo指简单的Java对象 是实体类Entity和 值对象VO 还有DTO数据传输对象的统称
Entity实体类,通常和对应的表字段的数量是一致的
DTO数据传输对象, 当客户端给服务器传递参数时,参数的数量可能比实体类中的数量要少,比如实体类中有10个参数 但是客户端只传递过来的3个参数,此时通过DTO接收传递过来的参数,如果使用实体类接收也可以但是会存在很多的null值,使用DTO好处是只要发现null值就能判断出传输出错了
VO值对象, 从数据库中的某个表查询数据,有多种场景,有的需要查全部,而有的查询只需要查一部分数据,如果只查一部分数据查询回来的数据直接用Entity接收封装的话,则Entity中会存在大量的null值, 这些null值传输给客户端也会占用流量,浪费资源,使用VO则可以解决此问题
5.在resources目录下创建mappers文件夹, 从苍老师文档服务器中找到mapper.xml配置文件下载下来放进此文件夹中改名为ProductMapper.xml
其中<mapper namespace="具体对应的mapper接口路径">
6.最后在SpringBoot工程中自带的单元测试类中进行测试
@Autowired(required = false)
ProductMapper mapper;
@Test
void contextLoads() {
Product p = new Product();
p.setTitle("xml标题");
p.setPrice(111.0);
p.setNum(222);
mapper.insert(p);
}
@Test
void t1(){
mapper.deleteById(1);
}
xml中基础增删改查
1.插入数据
<insert id="insert">
Insert INTO product Values(null,#{title},#{price},#{num})
</insert>
2.删除数据
<delete id="deleteById>
delete from product Where id=#{id}
</delete>
3.修改数据
<update id="update">
Update product Set title=#{title} , price=#{price},num=#{num}
</update>
4.查询数据
<select id="select" resultType="对应实体类路径">
Selete id,title,price,num From product
</select>
5.统计数量
<select id="count" resultType="int">
select count(*) FROM product
</select>
6.自动映射 resultMap
<select id="selectById" resultMap="productRM">
//SELECT id,title,sale_count,view_count FROM my_product(如果需要多次重用的话 用下列)
<include refid="query"></include>
WHERE id=#{id}
</select>
<resultMap id="productRM" type="实体类路径">
<result column="sale_count" property="saleCount"></result>
<result column="view_count" property="viewCount"></result>
</resultMap>
7.sql语句重用
<select id="select" resultMap="productRM">
<include refid="query"></include>
</select>
<!--定义复用的SQL语句-->
<sql id="query">
SELECT id,title,sale_count,view_count FROM my_product
</sql>
动态Sql
1.批量删除数据 如果参数类型是List集合则collection写list,如果不是则写array
mapper 接口中 int deleteByIds(List<Integer> ids)
int deleteByIds2(Integer[] ids);返回删除了多少行
<delete id="deleteByIds">
delete From product where id in(
<foreach collection="list" item="id" separator=",">
#{id}
</foreach>
)
</delete>
2.批量添加 ---如果有参数需要后端 设置默认写死 前端不传这个参数 像字段类型bit(1) 可以写true 也可写1 now()设置当前时间到表里
<insert id="insertAreas">
insert into service_area (cityCode,cityName,enable,activity,createrCode,addTime,isSetManager)
values
<foreach collection="list" item="item" separator=",">
(#{item.cityCode},#{item.cityName},1,1,#{sessionUserCode},now(),0)
</foreach>
</insert>
mapper接口中 //insert into product values(null,'',100,30),(null,'',100,30),(null,'',100,30)
//int insertProducts(List<Product> list);
<insert id="insertProducts">
INSERT INTO product
VALUES
<foreach collection="list" item="p" separator=",">
(
NULL ,#{p.title},#{p.price},#{p.num}
)
</foreach>
</insert>
3.批量查询
mapper接口中 // List<User> selectByIds(List<Integer> ids)
<select id="selectByIds" resultType="需要返回类型的路径 ,如果是要返回string 用java.lang.String">
select *
from User
where id in
<foreach collection="ids" item="p" open="(" close=")" separator=",">
#{id}
</foreach>
</select>
//动态插入数据,自动识别对象属性是否有值 ,suffixOverrides去掉多余的
mapper接口中 int dynamicInsert(Product product);
<insert id="dynamicInsert">
INSERT INTO product
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="title!=null">title,</if>
<if test="price!=null">price,</if>
<if test="num!=null">num</if>
</trim>
VALUES
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="title!=null">#{title},</if>
<if test="price!=null">#{price},</if>
<if test="num!=null">#{num}</if>
</trim>
</insert>
3.动态修改
mapper接口中 void dynamicUpdate(Product p);
<!--动态修改 set标签会自动去掉后面的逗号-->
<update id="dynamicUpdate">
UPDATE product
<set>
<if test="title!=null">title=#{title},</if>
<if test="price!=null">price=#{price},</if>
<if test="num!=null">num=#{num}</if>
</set>
WHERE id=#{id}
</update>
-------------------
多表联查时xml里要查询的涉及两张及以上表的信息
(resultmap需要映射里加映射)前提mapper方法的返回值实体类里一定要设计一个list包含一张表的信息
例如:
List<OrderListVO> selectOrdersBetweenTimes(OrderListTimeDTO orderListTimeDTO);
OrderListVO实体类里如下:
private Long id;
private Long userId;.......
private List<OrderItemListVO> orderItems;
OrderListVO类型中包含订单项的集合,需要进行映射编写 -->
包含集合的映射使用 collection 标签
----------property(必须): 指定要映射的集合类型的属性名称
----------javaType(可选): 指定当前集合的类型,默认类型是List,如果匹配无需编写
----------ofType(必须): 指定集合的泛型类型
<collection property="orderItems"
ofType="cn.tedu.mall.pojo.order.vo.OrderItemListVO">
<id column="ooi_id" property="id"/>
<result column="order_id" property="orderId"/>
..........
</collection>
要是不理解参考csmall-repo-class里roder>webapi>omsOrderMapper和它的xml
------------------------------------------------------------------------------------------------
动态修改------->使用原因是(表中很多数据可以支持修改 但不确定需要修改哪一个属性 )
可以使用动态修改 大大节省sql语句编写 不需要重复编写大量sql语句
动态修改的mapper方法()------>int updateOrderById(OmsOrder order);
xml里动态修改数据库中的sql语句,mybatis框架根据<set>标签会删除最后多余的 , 号
<update id="updateOrderById">
update oms_order
<set>
<if test="contactName!=null">
contact_name=#{contactName},
</if>
<if test="mobilePhone!=null">
mobile_phone=#{mobilePhone},
</if>
<if test="telephone!=null">
telephone=#{telephone},
</if>
</set>
where
id=#{id}
</update>