springboot整合Mybatis-Plus 實(shí)現(xiàn)代碼生成增刪改查
點(diǎn)擊上方藍(lán)色字體,選擇“標(biāo)星公眾號(hào)”
優(yōu)質(zhì)文章,第一時(shí)間送達(dá)
66套java從入門(mén)到精通實(shí)戰(zhàn)課程分享
springboot整合Mybatis-Plus 實(shí)現(xiàn)代碼生成增刪改查
spring boot 2.x
用user_plus表為實(shí)例
sql結(jié)構(gòu)
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
設(shè)置Mybatis-Plus分頁(yè)
/**
?*?配置分頁(yè)插件
?* mybatis - plus分頁(yè)插件MybatisPlusConfig:
?*/
@Configuration
public?class?MybatisPlusConfig?{
????/**
?????*?分頁(yè)插件
?????*/
????@Bean
????public?PaginationInterceptor?paginationInterceptor()?{
????????PaginationInterceptor?page?=?new?PaginationInterceptor();
????????//設(shè)置方言類(lèi)型
????????page.setDialectType("mysql");
????????return?page;
????}
}
代碼生成工具,自行改動(dòng)生成代碼的存放位置
public?class?CodeGenerator?{
????/**
?????*?
?????*?讀取控制臺(tái)內(nèi)容
?????*?
?????*/
????public?static?String?scanner(String?tip)?{
????????Scanner?scanner?=?new?Scanner(System.in);
????????StringBuilder?help?=?new?StringBuilder();
????????help.append("請(qǐng)輸入"?+?tip?+?":");
????????System.out.println(help.toString());
????????if?(scanner.hasNext())?{
????????????String?ipt?=?scanner.next();
????????????if?(StringUtils.isNotEmpty(ipt))?{
????????????????return?ipt;
????????????}
????????}
????????throw?new?MybatisPlusException("請(qǐng)輸入正確的"?+?tip?+?"!");
????}
?//運(yùn)行,填數(shù)據(jù)庫(kù)表名開(kāi)始生成代碼
????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 會(huì)自動(dòng)填充表實(shí)體屬性!
????????gc.setMapperName("%sMapper");
????????gc.setXmlName("%sMapper");
????????gc.setFileOverride(true);
????????gc.setActiveRecord(true);
????????//?XML?二級(jí)緩存
????????gc.setEnableCache(false);
????????//?XML?ResultMap
????????gc.setBaseResultMap(true);
????????//?XML?columList
????????gc.setBaseColumnList(false);
????????//?gc.setSwagger2(true);?實(shí)體屬性?Swagger2?注解
????????mpg.setGlobalConfig(gc);
????????//?數(shù)據(jù)源配置
????????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<>();
????????//?自定義配置會(huì)被優(yōu)先輸出
????????focList.add(new?FileOutConfig(templatePath)?{
????????????@Override
????????????public?String?outputFile(TableInfo?tableInfo)?{
????????????????//?自定義輸出文件名?,?如果你 Entity 設(shè)置了前后綴、此處注意 xml 的名稱(chēng)會(huì)跟著發(fā)生變化!!
????????????????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("表名,多個(gè)英文逗號(hào)分割").split(","));
????????strategy.setControllerMappingHyphenStyle(true);
????????strategy.setTablePrefix(pc.getModuleName()?+?"_");
????????mpg.setStrategy(strategy);
????????mpg.setTemplateEngine(new?FreemarkerTemplateEngine());
????????mpg.execute();
????}
}
這是我的完整目錄結(jié)構(gòu),怕出錯(cuò)的朋友可以按照此目錄操作
啟動(dòng)類(lèi)加上掃描mapper注解
@MapperScan("cn.theone.tmp.mybatisplus.mapper")
實(shí)體類(lèi)
@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類(lèi)
//默認(rèn)是沒(méi)有Repository注解和findAll方法的,接口可以自行擴(kuò)展
@Repository
public?interface?UserPlusMapper?extends?BaseMapper?{
????List?findAll();
}
Service接口和實(shí)現(xiàn)類(lèi)
//接口
public?interface?UserPlusService?extends?IService?{
????List?findAll();
}
//實(shí)現(xiàn)
@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類(lèi),默認(rèn)是沒(méi)有findAll方法的,自行擴(kuò)展的接口
"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"?/>
????
????
寫(xiě)測(cè)試類(lèi)測(cè)試
@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());
????????}
????}
}
默認(rèn)Mybatis-Plus已經(jīng)有非常全面的接口了,可以滿(mǎn)足大部分要求,有滿(mǎn)足不了的需求可以直接擴(kuò)展接口xml中寫(xiě)sql即可
至此Spring boot整合Mybatis-Plus 就完畢了
版權(quán)聲明:本文為博主原創(chuàng)文章,遵循 CC 4.0 BY-SA 版權(quán)協(xié)議,轉(zhuǎn)載請(qǐng)附上原文出處鏈接和本聲明。
本文鏈接:
https://blog.csdn.net/zgc55987/article/details/108941909
粉絲福利:108本java從入門(mén)到大神精選電子書(shū)領(lǐng)取
???
?長(zhǎng)按上方鋒哥微信二維碼?2 秒 備注「1234」即可獲取資料以及 可以進(jìn)入java1234官方微信群
感謝點(diǎn)贊支持下哈?
