SpringBoot_Mybatis MyBatisPlus

一.SpringBoot中使用Mybatis

springBoot中使用mybatis跟以前spring中使用方法一样.

1.mybatis配置:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/?useSSL=false&serverTimezone=Asia/Shanghai
    username: root
    password: ******
#mybatis配置
#需要配置别名的实体类的包
mybatis:
type-aliases-package: com.lanou.spring_bootm.entity
##mapper文件所在的位置
mapper-locations: classpath:mapper/*mapper.xml

2.配置mapper接口.

package com.lanou.spring_bootm.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.lanou.spring_bootm.entity.Emp;
import java.util.List;
public interface EmpMapper extends BaseMapper { List<Emp> findAll(); }

3.配置mapper文件.

在resources文件夹下创建mapper包

在mapper包中创建mapper.xml来写sql语句.

<?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.lanou.spring_bootm.mapper.EmpMapper">
    <select id="findAll" resultType="emp">
        select uuid,username,birthday,email from emp
    </select>
</mapper>

  

二.MybatisPlus

mybatisPlus是对mybatis的一个扩展.

使用mybatisplus直接将配置文件中mybatis改为mybatis-plus

mybatis-plus:
  type-aliases-package: com.lanou.spring_bootm.entity
  ##mapper文件所在的位置
  mapper-locations: classpath:mapper/*mapper.xml

mybatis-plus中定义好了很多对数据库简单的增删改查,和分页功能

用法很简单,将mapper中的接口继承于BaseMapper接口,

使用该接口中的方法不需要经过mapper.xml文件,

package com.lanou.spring_bootm.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.lanou.spring_bootm.entity.Emp;
import java.util.List;

//BaseMapper是mybatisplus中的接口 public interface EmpMapper extends BaseMapper { //自定义的查询方法,对应xml中的id List<Emp> findAll(); }

mybatis-plus中的分页功能需要要在config文件中配置Bean

//在springBoot中习惯使用java的配置方式进行配置
//SSM项目中也能用java方式进行配置

//这个注解相当于给这个类配置成配置文件. @Configuration public class MyBatisConfig { //配置MybatisPlus中的分页拦截 @Bean public PaginationInterceptor paginationInterceptor(){ return new PaginationInterceptor(); } }

  

猜你喜欢

转载自www.cnblogs.com/zhouchangyang/p/11125327.html