springboot整合Mybatis-Plus 实现代码生成增删改查
点击上方蓝色字体,选择“标星公众号”
优质文章,第一时间送达
springboot整合Mybatis-Plus 实现代码生成增删改查
spring boot 2.x
用user_plus表为实例
sql结构
CREATE TABLE `user_plus` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
pom文件
org.springframework.boot
spring-boot-starter-web
mysql
mysql-connector-java
runtime
org.springframework.boot
spring-boot-starter-freemarker
com.baomidou
mybatis-plus-boot-starter
2.3
com.alibaba
druid
1.1.5
org.projectlombok
lombok
true
org.springframework.boot
spring-boot-starter-test
test
org.junit.vintage
junit-vintage-engine
org.springframework.boot
spring-boot-maven-plugin
src/main/resources
**/*.properties
**/*.xml
**/*.yml
true
application文件
server:
port: 9999
spring:
application:
name: springboot-mybatisPlus
# database 部分注释
datasource:
type: com.alibaba.druid.pool.DruidDataSource
url: jdbc:mysql://localhost:3306/xxxx?useUnicode=true&characterEncoding=utf-8&useSSL=false&autoReconect=true&serverTimezone=GMT%2b8
username: xxxx
password: xxxx
driver-class-name: com.mysql.jdbc.Driver
filters: stat
maxActive: 50
initialSize: 0
maxWait: 60000
minIdle: 1
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: select 1 from dual
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxOpenPreparedStatements: 20
removeAbandoned: true
removeAbandonedTimeout: 180
mybatis-plus:
global-config:
# 逻辑删除配置
db-config:
# 删除前
logic-not-delete-value: 1
# 删除后
logic-delete-value: 0
configuration:
map-underscore-to-camel-case: true
auto-mapping-behavior: full
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
mapper-locations: classpath:mybatisplus/mapper/*.xml
设置Mybatis-Plus分页
/**
* 配置分页插件
* mybatis - plus分页插件MybatisPlusConfig:
*/
@Configuration
public class MybatisPlusConfig {
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor page = new PaginationInterceptor();
//设置方言类型
page.setDialectType("mysql");
return page;
}
}
代码生成工具,自行改动生成代码的存放位置
public class CodeGenerator {
/**
*
* 读取控制台内容
*
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
//运行,填数据库表名开始生成代码
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("vicente");
gc.setOpen(false);
// service 命名方式
gc.setServiceName("%sService");
// service impl 命名方式
gc.setServiceImplName("%sServiceImpl");
// 自定义文件命名,注意 %s 会自动填充表实体属性!
gc.setMapperName("%sMapper");
gc.setXmlName("%sMapper");
gc.setFileOverride(true);
gc.setActiveRecord(true);
// XML 二级缓存
gc.setEnableCache(false);
// XML ResultMap
gc.setBaseResultMap(true);
// XML columList
gc.setBaseColumnList(false);
// gc.setSwagger2(true); 实体属性 Swagger2 注解
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://127.0.0.1:3306/springboot-test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent("cn.theone.tmp.mybatisplus");
pc.setEntity("model");
pc.setService("service");
pc.setServiceImpl("service.impl");
pc.setController("controller");
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 如果模板引擎是 freemarker
String templatePath = "/templates/mapper.xml.ftl";
// 如果模板引擎是 velocity
// String templatePath = "/templates/mapper.xml.vm";
// 自定义输出配置
List focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
String moduleName = pc.getModuleName() == null ? "" : pc.getModuleName();
return projectPath + "/src/main/resources/mybatisplus/mapper/" + moduleName
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT + "xml";
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
这是我的完整目录结构,怕出错的朋友可以按照此目录操作
启动类加上扫描mapper注解
@MapperScan("cn.theone.tmp.mybatisplus.mapper")
实体类
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("user_plus")
public class UserPlus extends Model {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
private String name;
@Override
protected Serializable pkVal() {
return this.id;
}
}
Mapper类
//默认是没有Repository注解和findAll方法的,接口可以自行扩展
@Repository
public interface UserPlusMapper extends BaseMapper {
List findAll();
}
Service接口和实现类
//接口
public interface UserPlusService extends IService {
List findAll();
}
//实现
@Service
@Transactional(rollbackFor = Exception.class)
public class UserPlusServiceImpl extends ServiceImpl implements UserPlusService {
@Autowired
private UserPlusMapper userPlusMapper;
@Override
public List findAll() {
return userPlusMapper.findAll();
}
}
Mapper.xml类,默认是没有findAll方法的,自行扩展的接口
"1.0" encoding="UTF-8"?>
"-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
"cn.theone.tmp.mybatisplus.mapper.UserPlusMapper">
"BaseResultMap" type="cn.theone.tmp.mybatisplus.model.UserPlus">
"id" property="id" />
"name" property="name" />
写测试类测试
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = TmpApplication.class)
public class mybatisPlusTest {
@Autowired
private UserPlusService userPlusService;
@Test
public void findById() {
UserPlus userPlus = userPlusService.selectById(4);
System.out.println(userPlus.getName());
}
@Test
public void add() {
UserPlus user = new UserPlus();
user.setName("李四1");
userPlusService.insert(user);
}
@Test
public void update(){
UserPlus user = new UserPlus();
user.setId(4);
user.setName("李四111");
userPlusService.updateById(user);
}
@Test
public void delete(){
userPlusService.deleteById(4);
}
@Test
public void findAll(){
List userList = userPlusService.findAll();
for (UserPlus user : userList) {
System.out.println(user.getName());
}
}
}
默认Mybatis-Plus已经有非常全面的接口了,可以满足大部分要求,有满足不了的需求可以直接扩展接口xml中写sql即可
至此Spring boot整合Mybatis-Plus 就完毕了
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:
https://blog.csdn.net/zgc55987/article/details/108941909
粉丝福利:108本java从入门到大神精选电子书领取
???
?长按上方锋哥微信二维码 2 秒 备注「1234」即可获取资料以及 可以进入java1234官方微信群
感谢点赞支持下哈
评论