欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

淺談springboot中tk.mapper代碼生成器的用法說明

 更新時間:2020年09月29日 15:16:55   作者:xqnode  
這篇文章主要介紹了淺談springboot中tk.mapper代碼生成器的用法說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

問:什么是tk.mapper?

答:這是一個通用的mapper框架,相當(dāng)于把mybatis的常用數(shù)據(jù)庫操作方法封裝了一下,它實(shí)現(xiàn)了jpa的規(guī)范,簡單的查詢更新和插入操作都可以直接使用其自帶的方法,無需寫額外的代碼。

而且它還有根據(jù)實(shí)體的不為空的字段插入和更新的方法,這個是非常好用的哈。

而且它的集成非常簡單和方便,下面我來演示下使用它怎么自動生成代碼。

pom中引入依賴,這里引入tk.mybatis.mapper的版本依賴是因?yàn)樵趍apper-spring-boot-starter的新版本中沒有MapperPlugin這個類,無法提供代碼生成的功能,在老版本中有:

<!--通用mapper-->
<dependency>
 <groupId>tk.mybatis</groupId>
 <artifactId>mapper-spring-boot-starter</artifactId>
 <version>2.1.5</version>
</dependency>
<!--代碼生成使用-->
<dependency>
 <groupId>tk.mybatis</groupId>
 <artifactId>mapper</artifactId>
 <version>3.4.2</version>
</dependency>

配置generatorConfig.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
  PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<!-- 配置生成器 -->
<generatorConfiguration>
 <!--執(zhí)行g(shù)enerator插件生成文件的命令: call mvn mybatis-generator:generate -e -->
 <!-- 引入配置文件 -->
 <properties resource="generator.properties"/>
 <!--classPathEntry:數(shù)據(jù)庫的JDBC驅(qū)動,換成你自己的驅(qū)動位置 可選 -->
 <classPathEntry
   location="D:\iflytek\maven\repository\mysql\mysql-connector-java\8.0.15\mysql-connector-java-8.0.15.jar"/>

 <!-- 一個數(shù)據(jù)庫一個context -->
 <!--defaultModelType="flat" 大數(shù)據(jù)字段,不分表 -->
 <context id="MysqlTables" targetRuntime="MyBatis3Simple" defaultModelType="flat">
  <!-- 自動識別數(shù)據(jù)庫關(guān)鍵字,默認(rèn)false,如果設(shè)置為true,根據(jù)SqlReservedWords中定義的關(guān)鍵字列表;
  一般保留默認(rèn)值,遇到數(shù)據(jù)庫關(guān)鍵字(Java關(guān)鍵字),使用columnOverride覆蓋 -->
  <property name="autoDelimitKeywords" value="true"/>
  <!-- 生成的Java文件的編碼 -->
  <property name="javaFileEncoding" value="utf-8"/>
  <!-- beginningDelimiter和endingDelimiter:指明數(shù)據(jù)庫的用于標(biāo)記數(shù)據(jù)庫對象名的符號,比如ORACLE就是雙引號,MYSQL默認(rèn)是`反引號; -->
  <property name="beginningDelimiter" value="`"/>
  <property name="endingDelimiter" value="`"/>

  <!-- 格式化java代碼 -->
  <property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
  <!-- 格式化XML代碼 -->
  <property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>
  <plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
  <!--覆蓋xml文件-->
  <plugin type="com.xqnode.boot.util.OverwriteXmlPlugin"/>
  <!--toString-->
  <!--<plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>-->
  <plugin type="tk.mybatis.mapper.generator.MapperPlugin">
   <property name="mappers" value="tk.mybatis.mapper.common.Mapper"/>
  </plugin>

  <!-- 注釋 type="com.xqnode.boot.util.CommentGenerator" -->
  <commentGenerator>
   <property name="suppressAllComments" value="true"/><!-- 是否取消注釋 -->
   <property name="suppressDate" value="true"/> <!-- 是否生成注釋代時間戳-->
  </commentGenerator>

  <!-- jdbc連接 &amp;表示 & -->
  <jdbcConnection driverClass="${jdbc.driverClass}"
      connectionURL="${jdbc.connectionURL}"
      userId="${jdbc.userId}"
      password="${jdbc.password}"/>
  <!-- 類型轉(zhuǎn)換 -->
  <javaTypeResolver>
   <!-- 是否使用bigDecimal, false可自動轉(zhuǎn)化以下類型(Long, Integer, Short, etc.) -->
   <property name="forceBigDecimals" value="false"/>
  </javaTypeResolver>

  <!-- 生成實(shí)體類地址 -->
  <javaModelGenerator targetPackage="com.xqnode.boot.model" targetProject="src/main/java">
   <property name="enableSubPackages" value="false"/>
   <property name="trimStrings" value="true"/>
  </javaModelGenerator>
  <!-- 生成mapxml文件 -->
  <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
   <property name="enableSubPackages" value="false"/>
  </sqlMapGenerator>
  <!-- 生成mapxml對應(yīng)client,也就是接口dao -->
  <javaClientGenerator targetPackage="com.xqnode.boot.dao" targetProject="src/main/java"
        type="XMLMAPPER">
   <property name="enableSubPackages" value="false"/>
  </javaClientGenerator>
  <!-- table可以有多個,每個數(shù)據(jù)庫中的表都可以寫一個table,tableName表示要匹配的數(shù)據(jù)庫表,也可以在tableName屬性中通過使用%通配符來匹配所有數(shù)據(jù)庫表,只有匹配的表才會自動生成文件 -->
  <!-- tableName=% 則匹配數(shù)據(jù)庫的所有表,注意將domainObjectName和mapperName置為空-->
  <!-- enableCountByExample等設(shè)置生成簡單的crud操作方法-->
  <table tableName="${table.name}" domainObjectName="${domain.object.name}" mapperName="${mapper.name}">
   <property name="useActualColumnNames" value="false"/>
   <!-- 數(shù)據(jù)庫表主鍵 -->
   <generatedKey column="id" sqlStatement="Mysql" identity="true"/>
  </table>
 </context>
</generatorConfiguration>

基礎(chǔ)配置 generator.properties:

#jdbc
jdbc.driverClass=com.mysql.cj.jdbc.Driver
jdbc.connectionURL=jdbc:mysql://localhost:3306/test?serverTimezone=UTC&nullCatalogMeansCurrent=true
jdbc.userId=root
jdbc.password=123456

#project
project.name=springboot-mybatis

#table
table.name=t_user
domain.object.name=User
mapper.name=UserMapper

使用代碼的方式生成,工具GeneratorUtil:

package com.xqnode.boot.util;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 代碼生成工具 具體的配置在generator.properties中
 * create by qingxia4 on 2019/3/7 10:56
 */
public class GeneratorUtil {
 public static void main(String[] args) throws Exception {
  //MBG 執(zhí)行過程中的警告信息
  List<String> warnings = new ArrayList<>();
  //當(dāng)生成的代碼重復(fù)時,覆蓋原代碼
  boolean overwrite = true;
  //讀取我們的 MBG 配置文件
  InputStream is = GeneratorUtil.class.getResourceAsStream("/generatorConfig.xml");
  ConfigurationParser cp = new ConfigurationParser(warnings);
  Configuration config = cp.parseConfiguration(is);
  is.close();

  DefaultShellCallback callback = new DefaultShellCallback(overwrite);
  //創(chuàng)建 MBG
  MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
  //執(zhí)行生成代碼
  myBatisGenerator.generate(null);
  //輸出警告信息
  for (String warning : warnings) {
   System.err.println(warning);
  }
  System.out.println("-----success-----");
 }
}

這里還使用了一個覆蓋xml的插件OverwriteXmlPlugin,使用這個插件每次新生成的xml文件會完全覆蓋老的xml文件,這個插件已經(jīng)在上面的generatorConfig.xml中配置過了

package com.xqnode.boot.util;

import java.util.List;
import org.mybatis.generator.api.GeneratedXmlFile;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;

/**
 * @version 1.0.0
 */
public class OverwriteXmlPlugin extends PluginAdapter {

 @Override
 public boolean validate(List<String> warnings) {
  return true;
 }

 @Override
 public boolean sqlMapGenerated(GeneratedXmlFile sqlMap, IntrospectedTable introspectedTable) {
  sqlMap.setMergeable(false);
  return super.sqlMapGenerated(sqlMap, introspectedTable);
 }
}

最后,運(yùn)行GeneratorUtil 的main方法,就可以生成dao、model和mapper.xml文件了。而且生成的代碼非常簡潔,這是因?yàn)閠k.mapper代碼生成的插件中已經(jīng)做了相應(yīng)的處理。生成的結(jié)果如下:

使用:

首先在application.yml中配置xml和數(shù)據(jù)模型的位置:

mybatis:
 mapper-locations: classpath:mapper/*.xml
 type-aliases-package: com.xqnode.boot.model

然后在啟動類上加上注解@MapperScan(“com.xqnode.boot.dao”)掃描dao的位置,注意這個注解式來自tk.mybatis.spring.annotation包下的,千萬別引用錯了。

package com.xqnode.boot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import tk.mybatis.spring.annotation.MapperScan;

@SpringBootApplication
@MapperScan("com.xqnode.boot.dao")
public class Application {

 public static void main(String[] args) {
  SpringApplication.run(Application.class, args);
 }

}

現(xiàn)在就可以編寫controller測試了:

package com.xqnode.boot.controller;
import cn.hutool.crypto.SecureUtil;
import com.xqnode.boot.dao.UserMapper;
import com.xqnode.boot.model.User;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * created by xiaqing on 2019/3/6 20:11
 */
@RestController
@RequestMapping("/user")
public class UserController {

 @Resource
 private UserMapper userMapper;

 /**
  * 查詢所有用戶
  * @return
  */
 @GetMapping("/all")
 public List<User> findAll() {
  return userMapper.selectAll();
 }

 /**
  * 注冊新用戶
  * @param user
  * @return
  */
 @PostMapping("/registry")
 public Integer registry(@RequestBody User user) {
  String pwdMd5 = SecureUtil.md5(user.getPassword());
  user.setPassword(pwdMd5);
  user.setCreateTime(new Date());
  return userMapper.insertSelective(user);
 }

 /**
  * 根據(jù)登錄名修改密碼
  * @param user
  * @return
  */
 @PutMapping("/changePwd")
 public Integer changePwd(@RequestBody User user) {
  String pwdMd5 = SecureUtil.md5(user.getPassword());
  user.setPassword(pwdMd5);
  Example example = new Example(User.class);
  example.createCriteria().andEqualTo("loginName", user.getLoginName());
  return userMapper.updateByExampleSelective(user, example);
 }
}

接口訪問測試一下:

測試成功!

以上這篇淺談springboot中tk.mapper代碼生成器的用法說明就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • WeakHashMap的垃圾回收原理詳解

    WeakHashMap的垃圾回收原理詳解

    這篇文章主要介紹了WeakHashMap的垃圾回收原理詳解,WeakHashMap 與 HashMap 的用法基本類似,與 HashMap 的區(qū)別在于,HashMap的key保留了對實(shí)際對象的強(qiáng)引用個,這意味著只要該HashMap對象不被銷毀,該HashMap的所有key所引用的對象就不會被垃圾回收,需要的朋友可以參考下
    2023-09-09
  • Java保留兩位小數(shù)的實(shí)現(xiàn)方法

    Java保留兩位小數(shù)的實(shí)現(xiàn)方法

    這篇文章主要介紹了 Java保留兩位小數(shù)的實(shí)現(xiàn)方法的相關(guān)資料,需要的朋友可以參考下
    2017-06-06
  • Java動態(tài)數(shù)組ArrayList實(shí)現(xiàn)動態(tài)原理

    Java動態(tài)數(shù)組ArrayList實(shí)現(xiàn)動態(tài)原理

    ArrayList是一種動態(tài)數(shù)組,它可以在運(yùn)行時自動調(diào)整大小以適應(yīng)元素的添加和刪除,在Java中,你可以使用ArrayList類來實(shí)現(xiàn)動態(tài)數(shù)組,本文將給大家介紹一下ArrayList動態(tài)數(shù)組,是怎么實(shí)現(xiàn)動態(tài)的
    2023-08-08
  • 使用MyBatis進(jìn)行數(shù)據(jù)庫映射的方式

    使用MyBatis進(jìn)行數(shù)據(jù)庫映射的方式

    這篇文章主要介紹了使用MyBatis進(jìn)行數(shù)據(jù)庫映射的方式,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下
    2018-10-10
  • 關(guān)于HashMap相同key累加value的問題

    關(guān)于HashMap相同key累加value的問題

    這篇文章主要介紹了關(guān)于HashMap相同key累加value的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-05-05
  • java  List循環(huán)與Map循環(huán)的總結(jié)

    java List循環(huán)與Map循環(huán)的總結(jié)

    這篇文章主要介紹了java List循環(huán)與Map循環(huán)的總結(jié)的相關(guān)資料,并附代碼實(shí)例,幫助大家學(xué)習(xí)理解,需要的朋友可以參考下
    2016-11-11
  • Springboot項(xiàng)目啟動不加載resources目錄下的文件問題

    Springboot項(xiàng)目啟動不加載resources目錄下的文件問題

    這篇文章主要介紹了Springboot項(xiàng)目啟動不加載resources目錄下的文件問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-08-08
  • 關(guān)于重寫equals()方法和hashCode()方法及其簡單的應(yīng)用

    關(guān)于重寫equals()方法和hashCode()方法及其簡單的應(yīng)用

    這篇文章主要介紹了關(guān)于重寫equals()方法和hashCode()方法及其簡單的應(yīng)用,網(wǎng)上的知識有些可能是錯誤的,關(guān)于?equals()?方法的理解,大家討論不一樣,需要的朋友可以參考下
    2023-04-04
  • Spring-Boot 訪問外部接口的方案總結(jié)

    Spring-Boot 訪問外部接口的方案總結(jié)

    在Spring-Boot項(xiàng)目開發(fā)中,存在著本模塊的代碼需要訪問外面模塊接口,或外部url鏈接的需求,針對這一需求目前存在著三種解決方案,下面將對這三種方案進(jìn)行整理和說明,對Spring-Boot 訪問外部接口方案感興趣的朋友跟隨小編一起看看吧
    2022-12-12
  • Springcloud微服務(wù)架構(gòu)基礎(chǔ)知識解析

    Springcloud微服務(wù)架構(gòu)基礎(chǔ)知識解析

    這篇文章主要介紹了Springcloud微服務(wù)架構(gòu)基礎(chǔ)知識解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-04-04

最新評論