专栏首页后端Coderjava进阶|MyBatis系列文章(八)代码生成器

java进阶|MyBatis系列文章(八)代码生成器

一,MyBatis框架介绍

MyBatis是支持定制化SQL,存储过程以及高级映射的优秀的持久层框架。MyBatis避免了几乎所有的JDBC代码和手动参数以及获取结果集。MyBatis可以对配置和原生Map使用简单的XML或注解,将接口和Java的POJOS(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录。

二,项目需要的jar包信息,这里就将需要的pom文件信息全部贴出来了。

<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">    <modelVersion>4.0.0</modelVersion>    <parent>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-parent</artifactId>        <version>2.2.6.RELEASE</version>        <relativePath/> <!-- lookup parent from repository -->    </parent>    <groupId>com.wpw</groupId>    <artifactId>mybatis-annotation-page-helper</artifactId>    <version>0.0.1-SNAPSHOT</version>    <name>mybatis-annotation-page-helper</name>    <description>Demo project for Spring Boot</description>
    <properties>        <java.version>1.8</java.version>    </properties>
    <dependencies>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-web</artifactId>        </dependency>        <dependency>            <groupId>org.mybatis.spring.boot</groupId>            <artifactId>mybatis-spring-boot-starter</artifactId>            <version>2.1.2</version>        </dependency>
        <dependency>            <groupId>mysql</groupId>            <artifactId>mysql-connector-java</artifactId>            <scope>runtime</scope>        </dependency>        <dependency>            <groupId>org.projectlombok</groupId>            <artifactId>lombok</artifactId>            <optional>true</optional>        </dependency>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-test</artifactId>            <scope>test</scope>            <exclusions>                <exclusion>                    <groupId>org.junit.vintage</groupId>                    <artifactId>junit-vintage-engine</artifactId>                </exclusion>            </exclusions>        </dependency>        <!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper-spring-boot-starter -->        <dependency>            <groupId>com.github.pagehelper</groupId>            <artifactId>pagehelper-spring-boot-starter</artifactId>            <version>1.2.12</version>        </dependency>    </dependencies>
    <build>        <plugins>            <plugin>                <groupId>org.springframework.boot</groupId>                <artifactId>spring-boot-maven-plugin</artifactId>            </plugin>            <!-- mybatis generator 自动生成代码插件 -->            <plugin>                <groupId>org.mybatis.generator</groupId>                <artifactId>mybatis-generator-maven-plugin</artifactId>                <version>1.3.2</version>                <configuration>                    <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>                    <overwrite>true</overwrite>                    <verbose>true</verbose>                </configuration>                <!-- 配置数据库链接及mybatis generator core依赖 生成mapper时使用 -->                <dependencies>                    <dependency>                        <groupId>mysql</groupId>                        <artifactId>mysql-connector-java</artifactId>                        <version>5.1.46</version>                    </dependency>                    <dependency>                        <groupId>org.mybatis.generator</groupId>                        <artifactId>mybatis-generator-core</artifactId>                        <version>1.3.2</version>                    </dependency>                </dependencies>            </plugin>        </plugins>    </build>
</project>

感觉自己写的内容越来越相笔记了,哈哈哈,惭愧,就当做笔记看吧,主要还是给自己一个总结,避免以后遇到的时候方便查看。

三,项目需要的配置文件信息

server:  port: 8080spring:  datasource:    url: jdbc:mysql://localhost:3306/generator?serverTimezone=UTC    username: root    password: root    driver-class-name: com.mysql.cj.jdbc.Drivermybatis:  mapper-locations: classpath:mapper/**.xml  type-aliases-package: com.wpw.mybatisannotationpagehelper.pojo  configuration:    map-underscore-to-camel-case: onpagehelper:  reasonable: true

四,项目生成mapper文件信息的接口信息,配置信息如下

<?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>    <context id="DB2Tables" targetRuntime="MyBatis3">
        <commentGenerator>            <property name="suppressDate" value="true"/>            <!-- 是否去除自动生成的注释 true:是 : false:否 -->            <property name="suppressAllComments" value="true"/>        </commentGenerator>
        <!-- 数据库链接URL,用户名、密码 -->        <jdbcConnection driverClass="com.mysql.jdbc.Driver"                        connectionURL="jdbc:mysql://localhost:3306/generator?serverTimezone=UTC"                        userId="root"                        password="root">        </jdbcConnection>
        <!-- 类型转换 -->        <javaTypeResolver>            <!-- 是否使用BigDecimals,false可自动转化以下类型(Long Integer Short等) -->            <property name="forceBigDecimals" value="false"/>        </javaTypeResolver>
        <!-- 生成模型的包名和位置-->        <javaModelGenerator targetPackage="com.wpw.mybatisannotationpagehelper.pojo" targetProject="src/main/java">            <property name="enableSubPackages" value="true"/>            <property name="trimStrings" value="true"/>        </javaModelGenerator>
        <!-- 生成映射文件的包名和位置-->        <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">            <property name="enableSubPackages" value="true"/>        </sqlMapGenerator>
        <!-- 生成DAO的包名和位置 -->        <javaClientGenerator type="XMLMAPPER" targetPackage="com.wpw.mybatisannotationpagehelper.mapper" targetProject="src/main/java">            <property name="enableSubPackages" value="true"/>        </javaClientGenerator>
        <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->        <table tableName="user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false"               enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">            <property name="useActualColumnNames" value="false"/>            <!-- 数据库表主键 -->            <generatedKey column="id" sqlStatement="Mysql" identity="true"/>        </table>    </context>
</generatorConfiguration>

五,项目需要的sql文件信息

create database generator;use generator;select database();create table if not exists `user`(    id       int(11) primary key auto_increment comment '用户id,自增主键',    username varchar(255) comment '用户名',    password varchar(255) comment '用户密码',    phone    varchar(255) comment '用户手机号',    address  varchar(255) comment '用户地址',    id_card  varchar(255) comment '用户身份证') engine = InnoDB  charset = utf8 COMMENT '用户表';
insert into `user`(username, password, phone, address,id_card) values ("zhangsan","123456","13507660631","zheJiang","0001");insert into `user`(username, password, phone, address,id_card) values ("lsi","123456","13507660632","zheJiang","0002");insert into `user`(username, password, phone, address,id_card) values ("wangwu","123456","13507660633","zheJiang","0003");insert into `user`(username, password, phone, address,id_card) values ("zhaoliu","123456","13507660634","zheJiang","0004");insert into `user`(username, password, phone, address,id_card) values ("sunqi","123456","13507660635","zheJiang","0005");insert into `user`(username, password, phone, address,id_card) values ("dengchao","123456","13507660636","zheJiang","0006");insert into `user`(username, password, phone, address,id_card) values ("sunli","123456","13507660637","zheJiang","0007");insert into `user`(username, password, phone, address,id_card) values ("huangxiaoming","123456","13507660638","zheJiang","0008");insert into `user`(username, password, phone, address,id_card) values ("zhaowei","123456","13507660639","zheJiang","0009");insert into `user`(username, password, phone, address,id_card) values ("zhangsan","123456","13907660631","zheJiang","0010");insert into `user`(username, password, phone, address,id_card) values ("zhangsan","123456","13907660631","zheJiang","0010");insert into `user`(username, password, phone, address,id_card) values ("zhangsan001","123456","13907660631","zheJiang","0010");insert into `user`(username, password, phone, address,id_card) values ("zhangsan002","123456","13907660632","zheJiang","0010");insert into `user`(username, password, phone, address,id_card) values ("zhangsan003","123456","13907660633","zheJiang","0010");insert into `user`(username, password, phone, address,id_card) values ("zhangsan004","123456","13907660634","zheJiang","0010");insert into `user`(username, password, phone, address,id_card) values ("zhangsan005","123456","13907660635","zheJiang","0010");insert into `user`(username, password, phone, address,id_card) values ("zhangsan006","123456","13907660636","zheJiang","0010");insert into `user`(username, password, phone, address,id_card) values ("zhangsan007","123456","13907660637","zheJiang","0010");insert into `user`(username, password, phone, address,id_card) values ("zhangsan008","123456","13907660638","zheJiang","0010");insert into `user`(username, password, phone, address,id_card) values ("zhangsan009","123456","13907660639","zheJiang","0010");insert into `user`(username, password, phone, address,id_card) values ("zhangsan010","123456","13907660100","zheJiang","0010");

六,这篇文章主要为了自己去测试一下使用注解的方式,基于分页插件pageHelper进行分页,所以这里自己觉得xml在查询时太优秀了,所以以后会写xml文件对sql的操作,不会再写基于注解的方式进行分页查询的内容了,注解的方式其实对于单表操作很好用,但是对于动态sql方面我觉得没有xml方式好用。

package com.wpw.mybatisannotationpagehelper.controller;
import com.github.pagehelper.PageHelper;import com.wpw.mybatisannotationpagehelper.mapper.UserMapper;import com.wpw.mybatisannotationpagehelper.pojo.User;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/** * @author wpw */@RestControllerpublic class UserController {    private final UserMapper userMapper;
    public UserController(UserMapper userMapper) {        this.userMapper = userMapper;    }
    @PostMapping(value = "/list-pagination")    public List<User> listPagination(@RequestBody User user) {        PageHelper.startPage(user.getPageNumber(), user.getPageSize());        return userMapper.listPagination(user);    }
    @PostMapping(value = "/list")    public List<User> listPaginationByAnnotation(@RequestBody User user) {        PageHelper.startPage(user.getPageNumber(), user.getPageSize());        return userMapper.listPaginationByAnnotation(user);    }}

UserMapper接口代码信息如下

package com.wpw.mybatisannotationpagehelper.mapper;
import com.wpw.mybatisannotationpagehelper.pojo.User;import org.apache.ibatis.annotations.*;import org.apache.ibatis.jdbc.SQL;import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper@Repositorypublic interface UserMapper {    int deleteByPrimaryKey(Integer id);
    int insert(User record);
    int insertSelective(User record);
    User selectByPrimaryKey(Integer id);
    int updateByPrimaryKeySelective(User record);
    int updateByPrimaryKey(User record);
    List<User> listPagination(User user);
    @Results({            @Result(property = "username", column = "username"),            @Result(property = "password", column = "password"),            @Result(property = "phone", column = "phone"),            @Result(property = "idCard", column = "id_card"),            @Result(property = "address", column = "address")    })    @SelectProvider(type = UserSqlProvider.class, method = "listPaginationByAnnotation")    List<User> listPaginationByAnnotation(User user);

    class UserSqlProvider {        public String listPaginationByAnnotation(@Param("user") User user) {            SQL sql = new SQL() {                {                    SELECT("*");                    FROM("user");                    if (user.getUsername() != null && user.getUsername() != "") {                        WHERE("username like #{username}");                    }                    if (user.getPassword() != null && user.getPassword() != "") {                        WHERE("and password=#{password}");                    }                    if (user.getPhone() != null && user.getPhone() != "") {                        WHERE("and phone=#{phone}");                    }                }            };            return sql.toString();        }    }}

测试工具这里使用的是postman进行测试的,测试用例如下

点击下面的图示,生成pojo以及mapper信息。

代码的地址信息如下:

gitHub:https://github.com/myownmyway/mybatis-annotation-page-helper.git

整个搭建和测试的过程到这里就结束了,这里的代码已经很清楚的注释说明了,所以这里就不做过多的解释了,到这里MyBatis系列的文章就真正结束了,后面会在公众号里面补加一下菜单栏,就叫"MyBatis系列方便查找,这样也好自己查看和总结一下,好了,闲话也不闲扯了,喜欢的可以查看一下这这个系列的内容。

本文分享自微信公众号 - WwpwW(gh_245290c1861a),作者:后端Coder

原文出处及转载信息见文内详细说明,如有侵权,请联系 yunjia_community@tencent.com 删除。

原始发表时间:2020-04-19

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • 日志-logback

    终于有时间整理logback-spring.xml文件了,搭建完整的javaWeb项目也就缺少了这项基本技能了。不多介绍了,看下整个完整的项目项目搭建流程吧。

    后端Coder
  • java登录操作错误次数并发控制

    使用java写个登录错误限制次数限制的文章,毕竟写web项目,登录也是常见的一个操作,所以就有了这篇文章。

    后端Coder
  • java进阶|MySQL数据库系列文章(六)索引和视图操作

    索引,加快查询即数据的检索速度,但是又会增加磁盘空间的使用以及在数据的增删改操作中略微拖慢操作的速度,这就是简要的说下索引的好处和缺点,关于索引的内容,暂不对其...

    后端Coder
  • django搭建简易网站

    python3 manage.py startapp 应用名    #这里manage.py是创建完成django项目后产生的文件

    kirin
  • MyBatis-事务管理

    项目建立步骤: 1、在src目录下建立dp.properties文件,存放配置信息(需要自己在Oracle数据库建表)

    时间静止不是简史
  • 通过CREATE2获得合约地址:解决交易所充值账号问题

    CREATE2 是以太坊在2019年2月28号的君士坦丁堡(Constantinople)硬分叉[1]中引入 的一个新操作码。根据EIP1014[2]CREAT...

    Tiny熊
  • html+css学习笔记003-样式初始化

    Mr. 柳上原
  • 前端-HTML-web服务本质-HTTP协议-请求-标签-01(待完善)

    我们的浏览器端(B/S架构)本质上也是一个客户端,通过socket与服务端通信,发送请求,获得返回数据,再有浏览器将服务器返回的数据渲染成页面上看到的一个一个标...

    suwanbin
  • 五种类型的程序员,你属于哪一种?

    我把这些编码战士们分成五类,有些人是你队伍中的好伙伴,有些人则是捣蛋者,让你的每一个计划都完不成。

    良月柒
  • 让机器像人类一样学习? 伯克利 AI 研究院提出新的元强化学习算法!

    AI 科技评论按:如果要让机器人拥有人的学习能力,应该怎么做?伯克利 AI 研究院给出了一个很好的答案——元强化学习(meta-RL)。但这一次伯克利 AI 研...

    AI研习社

扫码关注云+社区

领取腾讯云代金券