項目基本目錄
注意:resources下的mbg生成的mapper.xml的文件夾不用建,自動生成
新建Spring Boot項目
新建Spring Boot項目,取好項目目錄名和項目名,一路Next
pom.xml
添加項目相關依賴
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<!--SpringBoot通用依賴模塊-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--MyBatis分頁插件-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.10</version>
</dependency>
<!--集成druid連接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<!-- MyBatis 生成器 -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.7</version>
</dependency>
<!--Mysql數據庫驅動-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
</dependencies>
注:只要整合了PagerHelper就自動整合了MyBatis。
application.yml
配置端口、數據源、掃描路徑
server:
port: 8080
spring:
datasource:
url: jdbc:mysql://localhost:3306/deliverysystem?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=CONVERT_TO_NULL
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
mapper-locations:
- classpath:mapper/*.xml
- classpath*:com/**/mapper/*.xml
新建包和文件
注:resources下的mbg生成的mapper.xml的文件不用建,自動生成
generator.properties
代碼生成器數據源配置
# jdbc
jdbc.driverClass = com.mysql.cj.jdbc.Driver
jdbc.connectionURL = jdbc:mysql://localhost:3306/deliverysystem?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=CONVERT_TO_NULL
jdbc.userId = root
jdbc.password = root
jdbc.maxPoolSize=50
jdbc.minPoolSize=10
jdbc.maxStatements=100
jdbc.testConnection=true
# mapper
# mapper.plugin = tk.mybatis.mapper.generator.MapperPlugin
# mapper.Mapper = com.jonychen.common.utils.CustomerMapper
MyCommentGenerator.java
自定義代碼註釋生成器
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.CompilationUnit;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.internal.DefaultCommentGenerator;
import org.mybatis.generator.internal.util.StringUtility;
import java.util.Properties;
/**
* 自定義註釋生成器
*/
public class MyCommentGenerator extends DefaultCommentGenerator {
private boolean addRemarkComments = false;
private static final String EXAMPLE_SUFFIX="Example";
// private static final String API_MODEL_PROPERTY_FULL_CLASS_NAME="io.swagger.annotations.ApiModelProperty";
/**
* 設置用戶配置的參數
*/
@Override
public void addConfigurationProperties(Properties properties) {
super.addConfigurationProperties(properties);
this.addRemarkComments = StringUtility.isTrue(properties.getProperty("addRemarkComments"));
}
/**
* 給字段添加註釋
*/
@Override
public void addFieldComment(Field field, IntrospectedTable introspectedTable,
IntrospectedColumn introspectedColumn) {
String remarks = introspectedColumn.getRemarks();
//根據參數和備註信息判斷是否添加備註信息
if(addRemarkComments&&StringUtility.stringHasValue(remarks)){
// addFieldJavaDoc(field, remarks);
//數據庫中特殊字符需要轉義
if(remarks.contains("\"")){
remarks = remarks.replace("\"","'");
}
//給model的字段添加swagger註解
//field.addJavaDocLine("@ApiModelProperty(value = \""+remarks+"\")");
}
}
/**
* 給model的字段添加註釋
*/
private void addFieldJavaDoc(Field field, String remarks) {
//文檔註釋開始
field.addJavaDocLine("/**");
//獲取數據庫字段的備註信息
String[] remarkLines = remarks.split(System.getProperty("line.separator"));
for(String remarkLine:remarkLines){
field.addJavaDocLine(" * "+remarkLine);
}
addJavadocTag(field, false);
field.addJavaDocLine(" */");
}
/* @Override
public void addJavaFileComment(CompilationUnit compilationUnit) {
super.addJavaFileComment(compilationUnit);
//只在model中添加swagger註解類的導入
if(!compilationUnit.isJavaInterface()&&!compilationUnit.getType().getFullyQualifiedName().contains(EXAMPLE_SUFFIX)){
compilationUnit.addImportedType(new FullyQualifiedJavaType(API_MODEL_PROPERTY_FULL_CLASS_NAME));
}
}*/
}
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>
<!--加載配置文件,爲下面讀取數據庫信息準備-->
<properties resource="generator.properties"/>
<!--
context:生成一組對象的環境
id:必選,上下文id,用於在生成錯誤時提示
defaultModelType:指定生成對象的樣式
1,conditional:類似hierarchical;
2,flat:所有內容(主鍵,blob)等全部生成在一個對象中;
3,hierarchical:主鍵生成一個XXKey對象(key class),Blob等單獨生成一個對象,其他簡單屬性在一個對象中(record class)
targetRuntime:
1,MyBatis3:默認的值,生成基於MyBatis3.x以上版本的內容,包括XXXBySample
2,MyBatis3Simple:類似MyBatis3,只是不生成XXXBySample;
introspectedColumnImpl:類全限定名,用於擴展MBG
-->
<context id="MySqlContext" targetRuntime="MyBatis3" defaultModelType="flat">
<!-- beginningDelimiter和endingDelimiter:指明數據庫的用於標記數據庫對象名的符號,比如ORACLE就是雙引號,MYSQL默認是`反引號-->
<property name="beginningDelimiter" value="`"/>
<property name="endingDelimiter" value="`"/>
<!-- 生成的Java文件的編碼 -->
<property name="javaFileEncoding" value="UTF-8"/>
<!-- 爲模型生成序列化方法-->
<plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
<!-- 爲生成的Java模型創建一個toString方法 -->
<plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
<!--覆蓋生成XML文件--><!--注意:這個pom.xml中MyBatis 生成器1.3.7版本纔有-->
<plugin type="org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin" />
<!--可以自定義生成model的代碼註釋-->
<!-- 阻止生成自動註釋 -->
<commentGenerator type="com.gxwz.deliverysystem.mbg.MyCommentGenerator">
<!-- 是否去除自動生成的註釋 true:是 : false:否 -->
<property name="javaFileEncoding" value="UTF-8"/>
<property name="suppressDate" value="true"/>
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--配置數據庫連接-->
<jdbcConnection driverClass="${jdbc.driverClass}"
connectionURL="${jdbc.connectionURL}"
userId="${jdbc.userId}"
password="${jdbc.password}">
<!--解決mysql驅動升級到8.0後不生成指定數據庫代碼的問題-->
<property name="nullCatalogMeansCurrent" value="true" />
</jdbcConnection>
<!--指定生成model的路徑--><!--targetProject="E:\ideaworkspace\mallstudy\src\main\java" (填絕對路徑)-->
<javaModelGenerator targetPackage="com.gxwz.deliverysystem.mbg.model" targetProject="E:\ideaworkspace\deliverysystem\src\main\java"/>
<!--指定生成mapper.xml的路徑-->
<sqlMapGenerator targetPackage="com.gxwz.deliverysystem.mbg.mapper" targetProject="E:\ideaworkspace\deliverysystem\src\main\resources"/>
<!--指定生成mapper接口的的路徑-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.gxwz.deliverysystem.mbg.mapper"
targetProject="E:\ideaworkspace\deliverysystem\src\main\java"/>
<!--生成全部表tableName設爲%-->
<!--<table tableName="%">
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table>-->
<!--要Example-->
<table tableName="pms_brand">
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table>
<!--不要Example-->
<!--<table tableName="cms_help" enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false">
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table>-->
</context>
</generatorConfiguration>
Generator.java
代碼生成器啓動類
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;
/**
* 用於生產MBG的代碼
* Created by macro on 2018/4/26.
*/
public class Generator {
public static void main(String[] args) throws Exception {
//MBG 執行過程中的警告信息
List<String> warnings = new ArrayList<String>();
//當生成的代碼重複時,覆蓋原代碼
boolean overwrite = true;
//讀取我們的 MBG 配置文件
InputStream is = Generator.class.getResourceAsStream("/generatorConfig.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(is);
is.close();
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
//創建 MBG
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
//執行生成代碼
myBatisGenerator.generate(null);
//輸出警告信息
for (String warning : warnings) {
System.out.println(warning);
}
}
}
運行Generator自動生成代碼
MybatisConfig.java
用於配置需要動態生成的mapper接口的路徑
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Configuration;
/**
* MyBatis配置類
* Created by macro on 2019/4/8.
*/
@Configuration
@MapperScan("com.gxwz.deliverysystem.mbg.mapper")
public class MyBatisConfig {
}
編寫Service接口
import com.gxwz.deliverysystem.mbg.model.User;
import java.util.List;
/**
* @author fengxiao
* @date 2020/2/23 17:28
*/
public interface UserService {
int createUser(User user);
int deleteUser(Long id);
int updateUser(Long id, User user);
List<User> listAllUser();
List<User> listUser(int pageNum, int pageSize);
User getUser(Long id);
}
編寫Service接口實現類
import com.github.pagehelper.PageHelper;
import com.gxwz.deliverysystem.mbg.mapper.UserMapper;
import com.gxwz.deliverysystem.mbg.model.User;
import com.gxwz.deliverysystem.mbg.model.UserExample;
import com.gxwz.deliverysystem.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
/**
* @author fengxiao
* @date 2020/2/23 17:36
*/
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public int createUser(User user){
return userMapper.insert(user);
}
@Override
public int deleteUser(Long id){
return userMapper.deleteByPrimaryKey(id);
}
@Override
public int updateUser(Long id, User user){
user.setId(id);
return userMapper.updateByPrimaryKey(user);
}
@Override
public List<User> listAllUser(){
return userMapper.selectByExample(new UserExample());
}
//分頁顯示
@Override
public List<User> listUser(int pageNum, int pageSize){
PageHelper.startPage(pageNum, pageSize);
return userMapper.selectByExample(new UserExample());
}
@Override
public User getUser(Long id){
return userMapper.selectByPrimaryKey(id);
}
}
添加common.api
包括對分頁數據和返回結果的封裝類
編寫Controller
import com.gxwz.deliverysystem.common.api.CommonPage;
import com.gxwz.deliverysystem.common.api.CommonResult;
import com.gxwz.deliverysystem.mbg.model.User;
import com.gxwz.deliverysystem.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* @author fengxiao
* @date 2020/2/23 18:00
*/
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);
/**
* 獲取所有User
* @return
*/
@RequestMapping(value = "/listAll", method = RequestMethod.GET)
@ResponseBody
public CommonResult<List<User>> getUserlist(){
return CommonResult.success(userService.listAllUser()); //成功時返回結果對象
}
/**
* 添加User
* @param user
* @return
*/
@RequestMapping(value = "/create", method = RequestMethod.POST)
@ResponseBody
public CommonResult createUser(@RequestBody User user) {
CommonResult commonResult;
int count = userService.createUser(user);
if (count == 1) {
commonResult = CommonResult.success(user);
LOGGER.debug("createUser success:{}", user);
} else {
commonResult = CommonResult.failed("操作失敗");
LOGGER.debug("createUser failed:{}", user);
}
return commonResult;
}
/**
* 根據id修改User
* @param id
* @param user
* @param result
* @return
*/
@RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
@ResponseBody
public CommonResult updateUser(@PathVariable("id") Long id, @RequestBody User user, BindingResult result) {
CommonResult commonResult;
int count = userService.updateUser(id, user);
if (count == 1) {
commonResult = CommonResult.success(user);
LOGGER.debug("updateUser success:{}", user);
} else {
commonResult = CommonResult.failed("操作失敗");
LOGGER.debug("updateUser failed:{}", user);
}
return commonResult;
}
/**
* 根據id刪除User
* @param id
* @return
*/
@RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
@ResponseBody
public CommonResult deleteUser(@PathVariable("id") Long id) {
int count = userService.deleteUser(id);
if (count == 1) {
LOGGER.debug("deleteUser success :id={}", id);
return CommonResult.success("操作成功");
} else {
LOGGER.debug("deleteUser failed :id={}", id);
return CommonResult.failed("操作失敗");
}
}
/**
* 分頁獲取User
* @param pageNum
* @param pageSize
* @return
*/
@RequestMapping(value = "/list", method = RequestMethod.GET)
@ResponseBody
public CommonResult<CommonPage<User>> listBrand(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
@RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {
List<User> userList = userService.listUser(pageNum, pageSize);
return CommonResult.success(CommonPage.restPage(userList));
}
/**
* 根據id獲取User
* @param id
* @return
*/
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
public CommonResult<User> brand(@PathVariable("id") Long id) {
return CommonResult.success(userService.getUser(id));
}
}