最近新开了个项目,记录第一次新开项目做得一些步骤,整合mybatis就是重要的一步,这里我演示了依赖的添加,逆向文件的生成。
先添加依赖,再增加配置文件
dependencies
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.5.2version>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plusartifactId>
<version>3.4.1version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.28version>
dependency>
build
<resources>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.*include>
includes>
resource>
resources>
mybatis-plus常见配置详解
mybatis-plus:
#xml扫描,多个目录用逗号或者分号分隔(告诉 Mapper 所对应的 XML 文件位置)
mapper-locations: classpath*:/mapper/*.xml
#MyBaits 别名包扫描路径,通过该属性可以给包中的类注册别名
type-aliases-package: com.rest.register.dao
configuration:
# 是否开启自动驼峰命名规则
map-underscore-to-camel-case: true
# 这个配置会将执行的sql打印出来,在开发或测试的时候可以用
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
global-config:
db-config:
# 默认id生成规则(assign_id雪花算法)
id-type: assign_id
多环境配置
spring:
profiles:
active: dev
---
spring:
config:
activate:
on-profile: dev
---
spring:
config:
activate:
on-profile: release
可以通过GeneratorConfig.xml这个配置文件,再执行命令实现将数据库的表转换成pojo对象类,并自动生成dao、mapper、pojo。
其实也就是使用mybatis-generator这个插件,增加依赖和增加插件就好。
<dependency>
<groupId>org.mybatis.generatorgroupId>
<artifactId>mybatis-generator-coreartifactId>
<version>1.3.7version>
dependency>
<plugin>
<groupId>org.mybatis.generatorgroupId>
<artifactId>mybatis-generator-maven-pluginartifactId>
<version>1.3.7version>
<configuration>
<configurationFile>${basedir}/src/main/resources/GeneratorConfig.xmlconfigurationFile>
<verbose>trueverbose>
<overwrite>trueoverwrite>
configuration>
plugin>
默认的mybatis-generator插件没有@Data注解,都是采用get和set,并且不能为字段增加注释。这里进行扩展,先写一个lombokPlugin,然后打包编译添加到jar包里的org.mybatis.generator.plugins目录下。(注意:这里替换的jar包得是idea编译用到的)
package org.mybatis.generator.plugins;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.Interface;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import org.mybatis.generator.internal.util.StringUtility;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
* 类描述:lombok自定义
*
* @ClassName LombokPlugin
* @Author ward
* @Date 2022-10-28 16:21
*/
public class LombokPlugin extends PluginAdapter {
@Override
public boolean validate(List<String> list) {
return true;
}
/**
* 为实体添加lombok的注解
*
* @param topLevelClass
* @param introspectedTable
* @return
*/
@Override
public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
//添加domain的import
topLevelClass.addImportedType("lombok.Data");
//添加domain的注解
topLevelClass.addAnnotation("@Data");
//添加domain的注释
topLevelClass.addJavaDocLine("/**");
topLevelClass.addJavaDocLine("* Created by Mybatis Generator on " + date2Str(new Date()));
topLevelClass.addJavaDocLine("*/");
return true;
}
/**
* 为实体类字段添加注释
*
* @param field
* @param topLevelClass
* @param introspectedColumn
* @param introspectedTable
* @param modelClassType
* @return
*/
@Override
public boolean modelFieldGenerated(Field field, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) {
field.addJavaDocLine("/**");
String remarks = introspectedColumn.getRemarks();
if (StringUtility.stringHasValue(remarks)) {
String[] remarkLines = remarks.split(System.getProperty("line.separator"));
for (String remarkLine : remarkLines) {
field.addJavaDocLine(" * " + remarkLine);
}
}
field.addJavaDocLine(" */");
return true;
}
/**
* mapper.xml的注释
*
* @param interfaze
* @param topLevelClass
* @param introspectedTable
* @return
*/
@Override
public boolean clientGenerated(Interface interfaze, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
//Mapper文件的注释
interfaze.addJavaDocLine("/**");
interfaze.addJavaDocLine("* Created by Mybatis Generator on " + date2Str(new Date()));
interfaze.addJavaDocLine("*/");
return true;
}
@Override
public boolean modelSetterMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) {
//不生成getter
return false;
}
@Override
public boolean modelGetterMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) {
//不生成setter
return false;
}
private String date2Str(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
return sdf.format(date);
}
}
配置文件放在指定目录下,pom.xml要做相应的配置。
DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<classPathEntry
location="D:\JavaJar\Frame\SSM\mysql-connector-java-8.0.28.jar"/>
<context id="DB2Tables" targetRuntime="MyBatis3">
<plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
<plugin type="org.mybatis.generator.plugins.LombokPlugin">
<property name="hasLombok" value="true"/>
plugin>
<commentGenerator>
<property name="suppressAllComments" value="true"/>
commentGenerator>
<jdbcConnection
driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/test"
userId="root"
password=""/>
<javaModelGenerator targetPackage="com.rest.register.pojo" targetProject="src/main/java">
javaModelGenerator>
<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
sqlMapGenerator>
<javaClientGenerator targetPackage="com.rest.register.mapper" targetProject="src/main/java"
type="XMLMAPPER">
javaClientGenerator>
<table tableName="user_account" domainObjectName="UserAccount"
enableCountByExample="false"
enableUpdateByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
selectByExampleQueryId="false">
table>
context>
generatorConfiguration>
然后找到项目里的这个插件,直接双击就会自动生成了。
@TableName(value = "t_User")
@Data
public class User extends Model<User>
implements Serializable {
public interface UserService extends IService<User> {
}
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
implements UserService {
@Override
public boolean save(DbSmartOrgPost entity) {
//重写个save方法
//todo:业务处理
this.baseMapper.insert(entity);
return true;
}
}
@RequestMapping("user")
public class NewsController {
@Resource
private UserService UserService ;
@PostMapping("/save")
public JsonResult<Boolean> save(@RequestBody User user) {
return JsonResult.success(UserService.save(user));
}
}
//插入一条记录(选择字段,策略插入)
default boolean save(T entity)
//批量插入
default boolean saveBatch(Collection<T> entityList)
//根据id删除
default boolean removeById(Serializable id)
//根据id修改
default boolean updateById(T entity)
//根据id查询
default T getById(Serializable id)
//查询(根据 columnMap 条件)
default List<T> listByMap(Map<String, Object> columnMap)
在sql中会使用到in查询,但是在mapper下不是简单的拼接,下面我做个错误示范:
select tel
from user
where ID in (#{userNames}))
这样会查不到数据,接下来我做个正确姿势,应该是使用for each,并且传递的时候用的是List《String》
select tel
from user
where ID in
<foreach collection="userNameArr"
item="item"
open="("
separator=","
close=")">
#{item,jdbcType=VARCHAR}
</foreach>
因为plugin和dependency的版本不一致导致的,所以在plugin的1.3.6里根本没找到我添加的lombok方法。