前言
mybatis自带代码生成插件,我们来试试如何使用
创建空项目
我们通过IDEA的Spring Intializr先创建一个sbm-generator的项目
目录结构
标红部分是代码生成器自动生成的代码,如何生成的请往下看
添加依赖
pom.xml引入代码生成依赖:
<?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 http://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.1.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.mrcoder</groupId>
<artifactId>sbm-generator</artifactId>
<version>0.0.1</version>
<name>sbm-generator</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</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<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.0.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<!--Mybatis-generator插件,用于自动生成Mapper和POJO-->
<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>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
<executions>
<execution>
<id>Generate MyBatis Artifacts</id>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.2</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
添加配置
application.yml:
spring:
datasource:
url: jdbc:mysql://192.168.145.131:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
mapper-locations: classpath:mapper/*.xml
#pagehelper分页插件
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
建库
建立test库,建表:
CREATE TABLE `person` (
`id` int(11) NOT NULL,
`name` varchar(255) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `person` VALUES ('1', '1', '1');
INSERT INTO `person` VALUES ('2', '2', '2');
INSERT INTO `person` VALUES ('3', '3', '3');
INSERT INTO `person` VALUES ('4', '4', '4');
INSERT INTO `person` VALUES ('5', '5', '5');
INSERT INTO `person` VALUES ('6', '6', '6');
INSERT INTO `person` VALUES ('7', '7', '7');
INSERT INTO `person` VALUES ('8', '8', '8');
INSERT INTO `person` VALUES ('9', '9', '9');
INSERT INTO `person` VALUES ('10', '10', '10');
INSERT INTO `person` VALUES ('11', '11', '11');
mybatis-generator的使用
在pom.xml我们配置了代码生成器配置的目录即
接下来我们就在对应的 /src/main/resources/generator/目录下创建此文件(generator文件夹请手动创建) 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>
<!-- 本地数据库驱动程序jar包的全路径 -->
<classPathEntry location="D:\MaveRepository\mysql\mysql-connector-java\8.0.15\mysql-connector-java-8.0.15.jar"/>
<context id="context" targetRuntime="MyBatis3">
<!-- optional,旨在创建class时,对注释进行控制 -->
<commentGenerator>
<property name="suppressAllComments" value="true"/>
<property name="suppressDate" value="true"/>
</commentGenerator>
<!-- 数据库的相关配置 -->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver" connectionURL="jdbc:mysql://192.168.145.131:3306/test"
userId="root" password="123456"/>
<!-- 非必需,类型处理器,在数据库类型和java类型之间的转换控制-->
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- Model实体类生成的位置 -->
<javaModelGenerator targetPackage="com.mrcoder.sbmgenerator.entity" targetProject="src/main/java">
<!-- 是否对model添加 构造函数 -->
<property name="constructorBased" value="false"/>
<!-- 是否允许子包,即targetPackage.schemaName.tableName -->
<property name="enableSubPackages" value="true"/>
<!-- 建立的Model对象是否 不可改变 即生成的Model对象不会有 setter方法,只有构造方法 -->
<property name="immutable" value="false"/>
<!-- 给Model添加一个父类 -->
<!--<property name="rootClass" value="com.foo.louis.Hello"/>-->
<!-- 是否对类CHAR类型的列的数据进行trim操作 -->
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- *Mapper.xml 文件的位置 -->
<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- Mapper 接口文件的位置 -->
<javaClientGenerator targetPackage="com.mrcoder.sbmgenerator.mapper" targetProject="src/main/java"
type="XMLMAPPER">
<property name="enableSubPackages" value="true"/>
<!--
定义Maper.java 源代码中的ByExample() 方法的可视性,可选的值有:
public;
private;
protected;
default
注意:如果 targetRuntime="MyBatis3",此参数被忽略
-->
<property name="exampleMethodVisibility" value=""/>
<!--方法名计数器Important note: this property is ignored if the target runtime is MyBatis3.-->
<property name="methodNameCalculator" value=""/>
<!--为生成的接口添加父接口-->
<property name="rootInterface" value=""/>
</javaClientGenerator>
<!-- 相关表的配置 -->
<table tableName="person" enableCountByExample="false" enableDeleteByExample="false"
enableSelectByExample="false"
enableUpdateByExample="false"/>
</context>
</generatorConfiguration>
相关配置的含义在代码中均有注释,请根据实际情况修改。
配置完成后,我们可以运行代码生成器mybatis-generator了,直接在IDEA右侧双击mybatis-generator:generate即可
运行成功会生成entity、mapper目录以及resources下的mapper目录。(参照上图目录结构)
完善
想要项目真正跑起来我们还得完善controller和service 我们在项目下右键新增controller和service的package, service下再新增implpackage,
service/PersonService.java:
package com.mrcoder.sbmgenerator.service;
import com.mrcoder.sbmgenerator.entity.Person;
import java.util.List;
public interface PersonService {
int addPerson(Person person);
List<Person> findAllPerson(int pageNum, int pageSize);
}
service/impl/PersonServiceImpl.java:
package com.mrcoder.sbmgenerator.service.impl;
import com.github.pagehelper.PageHelper;
import com.mrcoder.sbmgenerator.entity.Person;
import com.mrcoder.sbmgenerator.mapper.PersonMapper;
import com.mrcoder.sbmgenerator.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service(value = "personService")
public class PersonServiceImpl implements PersonService {
@Autowired
private PersonMapper personMapper;//这里会报错,但是并不会影响
@Override
public int addPerson(Person person) {
return personMapper.insert(person);
}
/*
* 这个方法中用到了我们开头配置依赖的分页插件pagehelper
* pageNum 开始页数
* pageSize 每页显示的数据条数
* */
@Override
public List<Person> findAllPerson(int pageNum, int pageSize) {
//将参数传给这个方法就可以实现物理分页了,非常简单。
PageHelper.startPage(pageNum, pageSize);
return personMapper.selectAllPerson();
}
}
mapper/PersonMapper.java:
package com.mrcoder.sbmgenerator.mapper;
import com.mrcoder.sbmgenerator.entity.Person;
import java.util.List;
public interface PersonMapper {
int insert(Person record);
int insertSelective(Person record);
//selectAllPerson是自己新增的查询方法
List<Person> selectAllPerson();
}
entity/Person.java:
package com.mrcoder.sbmgenerator.entity;
public class Person {
private Integer id;
private String name;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
controller/PersonController.java:
package com.mrcoder.sbmgenerator.controller;
import com.mrcoder.sbmgenerator.entity.Person;
import com.mrcoder.sbmgenerator.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class PersonController {
@Autowired
private PersonService personService;
@ResponseBody
@RequestMapping(value = "/all/{pageNum}/{pageSize}", produces = {"application/json;charset=UTF-8"})
public Object findAllPerson(@PathVariable("pageNum") int pageNum, @PathVariable("pageSize") int pageSize){
return personService.findAllPerson(pageNum,pageSize);
}
}
运行
运行项目,访问
项目地址
https://github.com/MrCoderStack/SpringBootDemo/tree/master/sbm-generator
https://gitee.com/MrCoderStack/SpringBootDemo/tree/master/sbm-generator