一,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系列方便查找,这样也好自己查看和总结一下,好了,闲话也不闲扯了,喜欢的可以查看一下这这个系列的内容。