河南循中网络科技有限公司 - 精心创作,详细分解,按照步骤,均可成功!
MyBatis-Plus是一个MyBatis的增强工具,只是在MyBatis的基础上做了增强却不做改变,MyBatis-Plus支持所有MyBatis原生的特性,所以引入MyBatis-Plus不会对现有的MyBatis构架产生任何影响。
MyBatis-Plus官网
【黑马MyBatisPlus教程全套视频教程,快速精通mybatisplus框架-哔哩哔哩】
无需勾选,直接下一步。
2. 配置父pom文件,声明:子模块。
common
mp
system
jar
1.8
1.18.24
1.2.11
3.5.1
3.5.3
2.3
org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-test
test
org.projectlombok
lombok
${lombok.version}
mysql
mysql-connector-java
runtime
com.alibaba
druid-spring-boot-starter
${druid-spring-boot-starter.version}
com.baomidou
mybatis-plus-boot-starter
${mybatis-plus-boot-starter.version}
com.baomidou
mybatis-plus-generator
${mybatis-plus-generator.version}
org.apache.velocity
velocity-engine-core
${velocity-engine-core.version}
5. 删除配置.properties,替换成.yaml配置。
# 主配置
# 选择环境
spring:
profiles:
active: dev
# mybatisPlus
mybatis-plus:
# 全局配置
global-config:
db-config:
# 主键ID生成策略
id-type: auto
# 逻辑删除策略
logic-delete-field: hide
logic-not-delete-value: 0
logic-delete-value: 1
# 开发环境
# 端口号
server:
port: 80
spring:
# 数据库
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: 路径
username: 令牌
password: 密码
# mybatisPlus
mybatis-plus:
# 开启mybatisPlus日志(输出到控制台)
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
package com.xz;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
import java.util.ArrayList;
import java.util.List;
public class Generator {
public static void main(String[] args) {
/*
特别注意:生成的时间类型均为:“LocalDateTime”格式,需要假如以下注解方可正常使用
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonSerialize(using = LocalDateTimeSerializer.class)
*/
//数据库连接
String url = "数据库URL";//数据库url
String username = "令牌";//账号
String password = "密码";//密码
String module = "mp";//模块名
//全局配置参数
String author = "河南循中网络科技有限公司";//作者
String outputDir = System.getProperty("user.dir")+"\\"+module+"\\src\\main\\java";//指定输出目录
//包配置参数
String parent = "com";//父包名
String moduleName = "xz";//父包模块名
String entity = "entity";//Entity 实体类包名
String mapper = "mapper";//Mapper 包名
String mapperXml = "mapper";//Mapper XML 包名
String service = "service";//Service 包名
String serviceImpl = "service.impl";//Service Impl 包名
/*String controller = "controller";//Controller 包名*/
//要生成的数据库表
List<String> tables = new ArrayList<>();
tables.add("product");
//开始生成
FastAutoGenerator.create(url,username,password)
//全局配置
.globalConfig(builder -> {
builder.author(author)
.outputDir(outputDir)
/*.enableSwagger()//开启swagger*/
.commentDate("yyyy-MM-dd");//注释日期
})
//包配置
.packageConfig(builder -> {
builder.parent(parent)
.moduleName(moduleName)
.entity(entity)
.mapper(mapper)
.xml(mapperXml)
.service(service)
.serviceImpl(serviceImpl)
/*.controller(controller)*/;
})
//策略配置
.strategyConfig(builder -> {
builder.addInclude(tables)
//开启生成实体类
.entityBuilder()
.enableLombok()//开启 lombok 模型
.enableTableFieldAnnotation()//开启生成实体时生成字段注解
//开启生成mapper
.mapperBuilder()
.enableBaseResultMap()//启用 BaseResultMap 生成
.superClass(BaseMapper.class)//设置父类
.enableMapperAnnotation()//开启 @Mapper 注解
.formatMapperFileName("%sMapper")//格式化 mapper 文件名称
.formatXmlFileName("%sMapper")//格式化 xml 实现类文件名称
//开启生成service及impl
.serviceBuilder()
.formatServiceFileName("%sService")//格式化 service 接口文件名称
.formatServiceImplFileName("%sServiceImpl");//格式化 service 实现类文件名称
/*//开启生成controller
.controllerBuilder()
// 映射路径使用连字符格式,而不是驼峰
.enableHyphenStyle()
.formatFileName("%sController")//格式化文件名称
.enableRestStyle();*/
})
.templateEngine(new VelocityTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
.templateConfig(builder -> builder.controller(""))//关闭生成controller
.execute();
}
}
如果数据库查询的时候有时间字段,并出现以下异常时:
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4f9eeeaa] was not registered for synchronization because synchronization is not active
JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@3cd18ac8] will not be managed by Spring
==> Preparing: SELECT product_id,one_classify_id,two_classify_id,three_classify_id,product_name,product_img,product_listimg,product_buying_price,product_original_price,minimum_profit_money,product_stock,product_sales,maximum_purchase,product_state,product_details,product_source,hide,update_time,insert_time FROM product WHERE product_id=? AND hide=0
==> Parameters: 2(Integer)
<== Columns: product_id, one_classify_id, two_classify_id, three_classify_id, product_name, product_img, product_listimg, product_buying_price, product_original_price, minimum_profit_money, product_stock, product_sales, maximum_purchase, product_state, product_details, product_source, hide, update_time, insert_time
<== Row: 2, 7, 9, 11, 勤啊, https://yang-1308989375.cos.ap-shanghai.myqcloud.com/upload/common/20220313/9496b05a-d696-4dfc-8dbd-ffaa174db62f.jpg, https://yang-1308989375.cos.ap-shanghai.myqcloud.com/upload/common/20220313/1b26cdf6-c119-4154-b38e-766e910c02ba.jpg,https://yang-1308989375.cos.ap-shanghai.myqcloud.com/upload/common/20220313/7d67c8ba-588f-418b-8417-6058a381beae.jpg,,, 0.5, 1.0, 0.5, 780, 18, null, 0, <<BLOB>>, 阳阳, 0, 2022-05-10 21:41:41, 2022-03-13 16:45:46
<== Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4f9eeeaa]
2022-08-07 17:57:07.811 ERROR 19424 --- [p-nio-80-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class java.time.LocalDateTime]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Java 8 date/time type `java.time.LocalDateTime` not supported by default: add Module "com.fasterxml.jackson.datatype:jackson-datatype-jsr310" to enable handling (through reference chain: com.xz.entity.Product["insertTime"])] with root cause
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Java 8 date/time type `java.time.LocalDateTime` not supported by default: add Module "com.fasterxml.jackson.datatype:jackson-datatype-jsr310" to enable handling (through reference chain: com.xz.entity.Product["insertTime"])
at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:77) ~[jackson-databind-2.13.3.jar:2.13.3]
at com.fasterxml.jackson.databind.SerializerProvider.reportBadDefinition(SerializerProvider.java:1300) ~[jackson-databind-2.13.3.jar:2.13.3]
at com.fasterxml.jackson.databind.ser.impl.UnsupportedTypeSerializer.serialize(UnsupportedTypeSerializer.java:35) ~[jackson-databind-2.13.3.jar:2.13.3]
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:728) ~[jackson-databind-2.13.3.jar:2.13.3]
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:774) ~[jackson-databind-2.13.3.jar:2.13.3]
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:178) ~[jackson-databind-2.13.3.jar:2.13.3]
at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider._serialize(DefaultSerializerProvider.java:480) ~[jackson-databind-2.13.3.jar:2.13.3]
at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:319) ~[jackson-databind-2.13.3.jar:2.13.3]
at com.fasterxml.jackson.databind.ObjectWriter$Prefetch.serialize(ObjectWriter.java:1518) ~[jackson-databind-2.13.3.jar:2.13.3]
at com.fasterxml.jackson.databind.ObjectWriter.writeValue(ObjectWriter.java:1007) ~[jackson-databind-2.13.3.jar:2.13.3]
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:456) ~[spring-web-5.3.21.jar:5.3.21]
at org.springframework.http.converter.AbstractGenericHttpMessageConverter.write(AbstractGenericHttpMessageConverter.java:104) ~[spring-web-5.3.21.jar:5.3.21]
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:290) ~[spring-webmvc-5.3.21.jar:5.3.21]
at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:183) ~[spring-webmvc-5.3.21.jar:5.3.21]
at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:78) ~[spring-web-5.3.21.jar:5.3.21]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:135) ~[spring-webmvc-5.3.21.jar:5.3.21]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895) ~[spring-webmvc-5.3.21.jar:5.3.21]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808) ~[spring-webmvc-5.3.21.jar:5.3.21]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.3.21.jar:5.3.21]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067) ~[spring-webmvc-5.3.21.jar:5.3.21]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963) ~[spring-webmvc-5.3.21.jar:5.3.21]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.3.21.jar:5.3.21]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.3.21.jar:5.3.21]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:655) ~[tomcat-embed-core-9.0.64.jar:4.0.FR]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.3.21.jar:5.3.21]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:764) ~[tomcat-embed-core-9.0.64.jar:4.0.FR]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.64.jar:9.0.64]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.3.21.jar:5.3.21]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.21.jar:5.3.21]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197) ~[tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) [tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) [tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135) [tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) [tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:360) [tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399) [tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:890) [tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1787) [tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) [tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) [tomcat-embed-core-9.0.64.jar:9.0.64]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.64.jar:9.0.64]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_181]
将项目改为web项目,增加web项目依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<?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>
<groupId>com.xz</groupId>
<artifactId>mp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mp</name>
<description>河南循中网络科技有限公司 - MyBatis-Plus自动化</description>
<!-- 子模块打包类型必须为jar -->
<packaging>jar</packaging>
<!-- parent指明继承关系,给出被继承的父项目的具体信息 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<!-- 版本控制 -->
<properties>
<java.version>1.8</java.version>
<!-- 实体类注解 -->
<lombok.version>1.18.24</lombok.version>
<!-- 数据库 -->
<druid-spring-boot-starter.version>1.2.11</druid-spring-boot-starter.version>
<!-- mybatis plus -->
<mybatis-plus-boot-starter.version>3.5.1</mybatis-plus-boot-starter.version>
<!-- mybatis代码生成器 -->
<mybatis-plus-generator.version>3.5.3</mybatis-plus-generator.version>
<!-- mybatis代码生成器,所需要的“velocity模板引擎” -->
<velocity-engine-core.version>2.3</velocity-engine-core.version>
<!-- swagger -->
<springfox-boot-starter.version>3.0.0</springfox-boot-starter.version>
</properties>
<!-- 引入的jar包 -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 实体类注解 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</dependency>
<!-- 数据库 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${druid-spring-boot-starter.version}</version>
</dependency>
<!-- mybatis plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus-boot-starter.version}</version>
</dependency>
<!-- mybatis代码生成器 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>${mybatis-plus-generator.version}</version>
</dependency>
<!-- mybatis代码生成器,所需要的“velocity模板引擎” -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>${velocity-engine-core.version}</version>
</dependency>
<!-- swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>${springfox-boot-starter.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
在实体类中,增加如下注解
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonSerialize(using = LocalDateTimeSerializer.class)