1. 程式人生 > 資料庫 >SpringBoot整合MySQL+MyBatis-1.0

SpringBoot整合MySQL+MyBatis-1.0

yaml配置檔案

  1. 連庫資訊
    mysql連庫資訊中,url拼接的引數:useUnicode=true&characterEncoding=utf-8指定字元的編碼、解碼格式;
    例如:MySQL資料中使用的編碼是GBK;而專案中使用的是utf-8;
  • 存資料時.
    資料庫中存放專案中輸入的資料時,會用UTF-8格式將資料解碼成位元組碼,然後再將解碼後的位元組碼重新使用GBK編碼將資料儲存到資料庫中;

  • 取資料時:
    在從資料庫中取資料的時候,資料庫會先將資料用GBK解碼成位元組碼,然後再將位元組碼用UTF-8格式編碼資料,最後再將資料返回給客戶端;

    serverTimezone時區=Asia/Shanghai

  1. 配置mybatis
  • 配置mybatis的對映路徑mapper-locations
    classpath*:支援後面的表示式使用萬用字元;
    **代表多級目錄
    mapper-locations支援配置陣列, - classpath為陣列中的一個元素
mybatis:
  mapper-locations:
    - classpath:mapper/*.xml
    - classpath*:com/**/mapper/*.xml
  • 掃描mapper包
@Configuration
@MapperScan("com.example.learning01.mbg.mapper")
public class MybatisConfig {
}

mybatis逆向工程

工程結構

  • 在mybatis-generator配置檔案中:
<javaModelGenerator/>、<sqlMapGenerator/>、<javaClientGenerator/>

這三個的targetProject的相對路徑配置規則是:
相對於工作空間的相對路徑,而在Idea中每個獨立專案就是一個工作空間,所以,這裡的相對路徑要配置成專案的檔案所在位置路徑。

<!--指定生成model的路徑-->
<javaModelGenerator targetPackage="com.example.learning01.mbg.model" targetProject="src\main\java"/>
<!--指定生成mapper.xml的路徑-->
<sqlMapGenerator targetPackage="com.example.learning01.mbg.mapper" targetProject="src\main\resources"/>
<!--指定生成mapper介面的的路徑-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.example.learning01.mbg.mapper"
                     targetProject="src\main\java"/>

mybatis分頁外掛

  • 在pom檔案中引入PageHelper外掛
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.2.10</version>
</dependency>
  • 配置分頁工具類
//常用
private Integer pageNum;
//常用
private Integer pageSize;

private Integer pageTotal;

private Long total;

private List<T> list;
//配置分頁物件,查詢結果通過呼叫restPage來實現分頁 list為查詢結果集
public static <T> CommonPagebak<T> restPage(List<T> list){
    CommonPagebak<T> result = new CommonPagebak<T>();
    PageInfo<T> pageInfo = new PageInfo<T>(list);
    result.setPageTotal(pageInfo.getPages());
    result.setPageNum(pageInfo.getPageNum());
    result.setPageSize(pageInfo.getPageSize());
    result.setTotal(pageInfo.getTotal());
    result.setList(pageInfo.getList());
    return  result;
}
  • service層啟用分頁外掛
@Override
public List<PmsBrand> listBrand(int pageNum, int pageSize) {
    //開啟分頁
    PageHelper.startPage(pageNum,pageSize);
    return pmsBrandMapper.selectByExample(new PmsBrandExample());
}
  • 控制層返回分頁結果
@GetMapping(value = "/list")
public CommenResult<CommonPagebak<PmsBrand>> listBrand(@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
                                                       @RequestParam(value = "pageSize",defaultValue = "3") Integer pageSize) {
    List<PmsBrand> result = pmsBrandService.listBrand(pageNum,pageSize);
    return CommenResult.success(CommonPagebak.restPage(result));
}