SpringBoot整合MyBatis


什么是mybaties

  • ​ MyBatis是一款優秀的支持自定義SQL查詢、存儲過程和高級映射的持久層框架,消除了幾乎所有的JDBC代碼和參數的手動設置以及結果集的檢索。MyBatis可以使用XML或注解進行配置和映射,MyBatis通過將參數映射到配置的SQL形成最終執行的SQL語句,最后將執行SQL的結果映射成Java對象返回

為什么MyBatis卻越來越受歡迎呢?

  • 1.不方便的全表映射,比如更新時需要發送所有的字段
  • 2.無法根據不同的條件組裝不同sql
  • 3.對多表關聯和復制sql查詢支持較差
  • 4.有HQL但性能較差,做不到sql優化
  • 5.不能有效支持存儲過程

MyBatis-Plus 插件(一個Mybatis框架的增強插件)

  • 1.只做增強不做改變,引入它不會對現有工程產生影響,如絲般順滑
  • 2.只需簡單配置,即可快速進行 CRUD 操作,從而節省大量時間
  • 3.熱加載、代碼生成、分頁、性能分析等功能一應俱全
  • 4.3.X系列支持lambda語法,讓我在寫條件構造的時候少了很多的"魔法值",從代碼結構上更簡潔

引入依賴

        <!-- mybatisPlus 核心庫 -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.1.0</version>
        </dependency>

配置

# 配置端口
server:
  port: 8888
spring:
  # 配置數據源
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mp_student?useUnicode=true&characterEncoding=utf-8
    username: root
    password: root
    type: com.alibaba.druid.pool.DruidDataSource
# mybatis-plus相關配置
mybatis-plus:
  # xml掃描,多個目錄用逗號或者分號分隔(告訴 Mapper 所對應的 XML 文件位置)
  mapper-locations: classpath:mapper/*.xml
  # 以下配置均有默認值,可以不設置
  global-config:
    db-config:
      #主鍵類型 AUTO:"數據庫ID自增" INPUT:"用戶輸入ID",ID_WORKER:"全局唯一ID (數字類型唯一ID)", UUID:"全局唯一ID UUID";
      id-type: auto
      #字段策略 IGNORED:"忽略判斷"  NOT_NULL:"非 NULL 判斷")  NOT_EMPTY:"非空判斷"
      field-strategy: NOT_EMPTY
      #數據庫類型
      db-type: MYSQL
  configuration:
    # 是否開啟自動駝峰命名規則映射:從數據庫列名到Java屬性駝峰命名的類似映射
    map-underscore-to-camel-case: true
    # 如果查詢結果中包含空值的列,則 MyBatis 在映射的時候,不會映射這個字段
    call-setters-on-nulls: true
    # 這個配置會將執行的sql打印出來,在開發或測試的時候可以用
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

基礎類

啟動類增加掃描包注解

@MapperScan(basePackages = {"com.mp.demo.dao"}) //掃描DAO

Config配置類(配置分頁插件)

/**
 * @Description MybatisPlus配置類
 */
@Configuration
public class MybatisPlusConfig {
    /**
     * mybatis-plus SQL執行效率插件
     */
    @Bean
    public PerformanceInterceptor performanceInterceptor() {
        return new PerformanceInterceptor();
    }
    /**
     * 分頁插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}

Dao類

/**
 * @Description 用戶信息DAO
 */
public interface UserInfoDao extends BaseMapper<UserInfoEntity> {
}

Service類

/**
 * @Description 用戶業務接口
 */
public interface UserInfoService extends IService<UserInfoEntity> {
}

ServiceImpl類

/**
 * @Description 用戶業務實現
 */
@Service
@Transactional
public class UserInfoSerivceImpl extends ServiceImpl<UserInfoDao, UserInfoEntity> implements UserInfoService {
}

MyBatis-Plus基礎使用

根據ID獲取用戶信息

    @GetMapping("/getInfo/{userId}")
    public UserInfoEntity getInfo(@PathVariable("userId") String userId) {
        UserInfoEntity userInfoEntity = userInfoService.getById(userId);
        return userInfoEntity;
    }

查詢全部信息

@GetMapping("/getList")
    public List<UserInfoEntity> getList() {
        List<UserInfoEntity> userInfoEntityList = userInfoService.list();
        return userInfoEntityList;
    }

分頁查詢全部數據

    @GetMapping("/getInfoListPage")
    public IPage<UserInfoEntity> getInfoListPage() {  //IPage<UserInfoEntity> 分頁數據
        //需要在Config配置類中配置分頁插件
        IPage<UserInfoEntity> page = new Page<>();
        page.setCurrent(1); //頁數
        page.setSize(3);    //每頁條數
        //條件構造
        QueryWrapper queryWrapper =new QueryWrapper();
        queryWrapper.ge("age", 22);

        page = userInfoService.page(page,queryWrapper);
        return page;
    }

指定字段查詢用戶信息

@GetMapping("/getList")
    public Collection<UserInfoEntity> getListMap() {
        Map<String, Object> map = new HashMap<>();
        //key:字段名 value:值
        map.put("name", "小趙");
        Collection<UserInfoEntity> userInfoList = userInfoService.listByMap(map);
        return userInfoList;
    }

新增

    @GetMapping("/saveInfo")
    public void saveInfo() {
        UserInfoEntity userInfoEntity = new UserInfoEntity();
        userInfoEntity.setName("小趙");
        userInfoEntity.setAge(18);
        userInfoService.save(userInfoEntity);
    }

批量新增

    @GetMapping("/saveInfoList")
    public void saveInfoList() {
        //創建對象
        UserInfoEntity xiaoli = new UserInfoEntity();
        sans.setName("小李");
        sans.setAge(18);
        UserInfoEntity xiaozhao = new UserInfoEntity();
        papyrus.setName("小趙");
        papyrus.setAge(18);
        //批量保存
        List<UserInfoEntity> list = new ArrayList<>();
        list.add(xiaoli);
        list.add(xiaozhao);
        userInfoService.saveBatch(list);
    }

更新

    @GetMapping("/updateInfo")
    public void updateInfo() {
        //根據實體中的ID去更新,其他字段如果值為null則不會更新該字段,參考yml配置文件
        UserInfoEntity userInfoEntity = new UserInfoEntity();
        userInfoEntity.setId(1);
        userInfoEntity.setAge(19);
        userInfoService.updateById(userInfoEntity);
    }

新增或者更新

    @GetMapping("/saveOrUpdate")
    public void saveOrUpdate() {
        //實體類ID值存在,如果數據庫存在ID就會更新,如果不存在就會新增
        UserInfoEntity userInfoEntity = new UserInfoEntity();
        userInfoEntity.setId(1);
        userInfoEntity.setAge(20);
        userInfoService.saveOrUpdate(userInfoEntity);
    }

根據ID刪除

    @DeleteMapping("/deleteInfo/{userId}")
    public void deleteInfo(@PathVariable("userId") String userId) {
        userInfoService.removeById(userId);
    }

根據ID批量刪除

    @GetMapping("/deleteList")
    public void deleteInfoList() {
        List<String> userIdlist = new ArrayList<>();
        userIdlist.add("1");
        userIdlist.add("2");
        userInfoService.removeByIds(userIdlist);
    }

根據指定字段刪除

    @GetMapping("/deleteInfo")
    public void deleteInfoMap() {
        //key:字段名 value:值
        Map<String, Object> map = new HashMap<>();
        map.put("name", "小李");
        map.put("age", 10);
        userInfoService.removeByMap(map);
    }

條件構造器(QueryWrapper)

查詢 說明
setSqlSelect 設置 SELECT 查詢字段
where WHERE 語句
and AND 語句
or OR 語句
eq 等於
allEq 基於 map 內容等於
ne 不等於<>
gt 大於
ge 大於等於
lt 小於
le 小於等於
like 模糊查詢
notLike 模糊查詢
in IN 查詢
notIn NOT IN 查詢
isNull NULL 值查詢
isNotNull 非 NULL 值查詢
groupBy 分組查詢
having 關鍵詞查詢
orderBy 排序
orderByAsc ASC 排序
orderByDesc DESC 排序
exists 果子查詢(返回包含行,則返回 TRUE)
notExists
between BETWEEN 查詢
notBetween
addFilter 自由拼接
last 拼接在最后, 例:last("LIMIT 10")


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM