电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

SpringBoot+MybatisPlus+代碼生成器整合示例

瀏覽:5日期:2023-05-27 10:14:02

項(xiàng)目目錄結(jié)構(gòu):

SpringBoot+MybatisPlus+代碼生成器整合示例

pom文件:

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd'> <modelVersion>4.0.0</modelVersion> <groupId>com.warrior</groupId> <artifactId>ETH</artifactId> <version>1.0-SNAPSHOT</version> <!-- Inherit defaults from Spring Boot --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.0.BUILD-SNAPSHOT</version> </parent> <!-- Add typical dependencies for a web application --> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- mybatis的orm插件 --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatisplus-spring-boot-starter</artifactId> <version>1.0.4</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus</artifactId> <version>2.0.7</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.velocity/velocity --> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity</artifactId> <version>1.7</version> </dependency> <!-- https://mvnrepository.com/artifact/org.freemarker/freemarker --> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.28</version> </dependency> <!--數(shù)據(jù)庫(kù)連接jdbc依賴(lài)--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!--mysql鏈接依賴(lài)--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!--阿里druid數(shù)據(jù)庫(kù)鏈接依賴(lài)--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.9</version> </dependency> <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>0.10.1</version> <scope>provided</scope> </dependency> </dependencies> <!-- Package as an executable jar --> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> <!-- Add Spring repositories --> <!-- (you don’t need this if you are using a .RELEASE version) --> <repositories> <repository> <id>spring-snapshots</id> <url>http://repo.spring.io/snapshot</url> <snapshots> <enabled>true</enabled> </snapshots> </repository> <repository> <id>spring-milestones</id> <url>http://repo.spring.io/milestone</url> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>spring-snapshots</id> <url>http://repo.spring.io/snapshot</url> </pluginRepository> <pluginRepository> <id>spring-milestones</id> <url>http://repo.spring.io/milestone</url> </pluginRepository> </pluginRepositories></project>

Application

package com.warrior;import org.mybatis.spring.annotation.MapperScan;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.EnableAutoConfiguration;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody; @SpringBootApplication@MapperScan('com.warrior.mapper') //配置mapper掃描public class Application { public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); }}

application.properties

#默認(rèn)啟用開(kāi)發(fā)環(huán)境配置spring.profiles.active=dev#啟用生產(chǎn)環(huán)境配置#spring.profiles.active=pro

application-dev.properties

server.port=8080spring.datasource.type=com.alibaba.druid.pool.DruidDataSourcespring.datasource.url=jdbc:mysql://localhost:3306/ethspring.datasource.username=rootspring.datasource.password=123456spring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.max-idle=10spring.datasource.max-wait=10000spring.datasource.min-idle=5spring.datasource.initial-size=5mybatis-plus.mapper-locations=classpath:/mapper/*Mapper.xmlmybatis-plus.typeAliasesPackage=com.cn.restyle.entity

配置文件:

1).

package com.warrior.config; import javax.sql.DataSource; import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.jdbc.datasource.DataSourceTransactionManager; import com.alibaba.druid.pool.DruidDataSource; /** * 數(shù)據(jù)源配置 */@Configurationpublic class DataSourceConfig { @Bean(name='dataSource') @ConfigurationProperties(prefix='spring.datasource') public DataSource dataSource(){ return new DruidDataSource(); } // 配置事物管理器 @Bean(name='transactionManager') public DataSourceTransactionManager transactionManager(){ return new DataSourceTransactionManager(dataSource()); } }

2). MybatisPlusConfig.java:

package com.warrior.config; import org.mybatis.spring.annotation.MapperScan;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import com.baomidou.mybatisplus.plugins.PaginationInterceptor; @Configuration//掃描dao或者是Mapper接口@MapperScan('com.warrior.mapper*')public class MybatisPlusConfig { /** * mybatis-plus 分頁(yè)插件 */ @Bean public PaginationInterceptor paginationInterceptor(){ PaginationInterceptor page = new PaginationInterceptor(); page.setDialectType('mysql'); return page; } }

生成代碼:

1).mysql數(shù)據(jù)庫(kù)建表

SpringBoot+MybatisPlus+代碼生成器整合示例

2).代碼生成器MpGenenator.java

import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map; import com.baomidou.mybatisplus.generator.AutoGenerator;import com.baomidou.mybatisplus.generator.InjectionConfig;import com.baomidou.mybatisplus.generator.config.*;import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;import com.baomidou.mybatisplus.generator.config.po.TableInfo;import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;import com.baomidou.mybatisplus.generator.config.rules.DbType;import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; /** * <p> * 代碼生成器演示 * </p> */public class MpGenerator { final static String dirPath = 'D://'; /** * <p> * MySQL 生成演示 * </p> */ public static void main(String[] args) { AutoGenerator mpg = new AutoGenerator(); // 選擇 freemarker 引擎,默認(rèn) Veloctiy //mpg.setTemplateEngine(new FreemarkerTemplateEngine()); // 全局配置 GlobalConfig gc = new GlobalConfig(); gc.setOutputDir(dirPath); gc.setAuthor('lqh'); gc.setFileOverride(true); //是否覆蓋 gc.setActiveRecord(true);// 不需要ActiveRecord特性的請(qǐng)改為false gc.setEnableCache(false);// XML 二級(jí)緩存 gc.setBaseResultMap(true);// XML ResultMap gc.setBaseColumnList(true);// XML columList // 自定義文件命名,注意 %s 會(huì)自動(dòng)填充表實(shí)體屬性! // gc.setMapperName('%sDao'); // gc.setXmlName('%sMapper'); // gc.setServiceName('MP%sService'); // gc.setServiceImplName('%sServiceDiy'); // gc.setControllerName('%sAction'); mpg.setGlobalConfig(gc); // 數(shù)據(jù)源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setDbType(DbType.MYSQL); dsc.setTypeConvert(new MySqlTypeConvert(){ // 自定義數(shù)據(jù)庫(kù)表字段類(lèi)型轉(zhuǎn)換【可選】 @Override public DbColumnType processTypeConvert(String fieldType) { System.out.println('轉(zhuǎn)換類(lèi)型:' + fieldType); // 注意!!processTypeConvert 存在默認(rèn)類(lèi)型轉(zhuǎn)換,如果不是你要的效果請(qǐng)自定義返回、非如下直接返回。 return super.processTypeConvert(fieldType); } }); dsc.setDriverName('com.mysql.jdbc.Driver'); dsc.setUsername('root'); dsc.setPassword('123456'); dsc.setUrl('jdbc:mysql://127.0.0.1:3306/eth?characterEncoding=utf8'); mpg.setDataSource(dsc); // 策略配置 StrategyConfig strategy = new StrategyConfig(); // strategy.setCapitalMode(true);// 全局大寫(xiě)命名 ORACLE 注意 strategy.setTablePrefix(new String[] { 'tb_', 'tsys_' });// 此處可以修改為您的表前綴 strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略 // strategy.setInclude(new String[] { 'user' }); // 需要生成的表 // strategy.setExclude(new String[]{'test'}); // 排除生成的表 // 自定義實(shí)體父類(lèi) // strategy.setSuperEntityClass('com.baomidou.demo.TestEntity'); // 自定義實(shí)體,公共字段 // strategy.setSuperEntityColumns(new String[] { 'test_id', 'age' }); // 自定義 mapper 父類(lèi) // strategy.setSuperMapperClass('com.baomidou.demo.TestMapper'); // 自定義 service 父類(lèi) // strategy.setSuperServiceClass('com.baomidou.demo.TestService'); // 自定義 service 實(shí)現(xiàn)類(lèi)父類(lèi) // strategy.setSuperServiceImplClass('com.baomidou.demo.TestServiceImpl'); // 自定義 controller 父類(lèi) // strategy.setSuperControllerClass('com.baomidou.demo.TestController'); // 【實(shí)體】是否生成字段常量(默認(rèn) false) // public static final String ID = 'test_id'; // strategy.setEntityColumnConstant(true); // 【實(shí)體】是否為構(gòu)建者模型(默認(rèn) false) // public User setName(String name) {this.name = name; return this;} strategy.setEntityBuilderModel(true); mpg.setStrategy(strategy); // 包配置 PackageConfig pc = new PackageConfig(); pc.setParent('com'); pc.setModuleName('warrior'); pc.setController('controler'); pc.setEntity('entity'); pc.setMapper('mapper'); pc.setService('service'); pc.setServiceImpl('serviceImpl'); pc.setXml('mapperXml'); mpg.setPackageInfo(pc); // 注入自定義配置,可以在 VM 中使用 cfg.abc 【可無(wú)】 InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() { Map<String, Object> map = new HashMap<String, Object>(); map.put('abc', this.getConfig().getGlobalConfig().getAuthor() + '-mp'); this.setMap(map); } }; // 自定義 xxList.jsp 生成 List<FileOutConfig> focList = new ArrayList<FileOutConfig>();/* focList.add(new FileOutConfig('/template/list.jsp.vm') { @Override public String outputFile(TableInfo tableInfo) { // 自定義輸入文件名稱(chēng) return 'D://my_' + tableInfo.getEntityName() + '.jsp'; } }); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg);*/ // 調(diào)整 xml 生成目錄演示/* focList.add(new FileOutConfig('/templates/mapper.xml.vm') { @Override public String outputFile(TableInfo tableInfo) { return dirPath + tableInfo.getEntityName() + 'Mapper.xml'; } }); cfg.setFileOutConfigList(focList); */ mpg.setCfg(cfg); // 關(guān)閉默認(rèn) xml 生成,調(diào)整生成 至 根目錄/* TemplateConfig tc = new TemplateConfig(); tc.setXml(null); mpg.setTemplate(tc);*/ // 自定義模板配置,可以 copy 源碼 mybatis-plus/src/main/resources/templates 下面內(nèi)容修改, // 放置自己項(xiàng)目的 src/main/resources/templates 目錄下, 默認(rèn)名稱(chēng)一下可以不配置,也可以自定義模板名稱(chēng) // TemplateConfig tc = new TemplateConfig(); // tc.setController('...'); // tc.setEntity('...'); // tc.setMapper('...'); // tc.setXml('...'); // tc.setService('...'); // tc.setServiceImpl('...'); // 如上任何一個(gè)模塊如果設(shè)置 空 OR Null 將不生成該模塊。 // mpg.setTemplate(tc); // 執(zhí)行生成 mpg.execute(); // 打印注入設(shè)置【可無(wú)】 System.err.println(mpg.getCfg().getMap().get('abc')); } }

生成的文件如下,只要將對(duì)應(yīng)文件拷到項(xiàng)目對(duì)應(yīng)包即可:

SpringBoot+MybatisPlus+代碼生成器整合示例

下面把對(duì)應(yīng)類(lèi)展示出來(lái):

.entity-->Student.java

package com.warrior.entity; import com.baomidou.mybatisplus.enums.IdType;import com.baomidou.mybatisplus.annotations.TableId;import com.baomidou.mybatisplus.annotations.TableField;import com.baomidou.mybatisplus.activerecord.Model;import com.baomidou.mybatisplus.annotations.TableName;import java.io.Serializable; /** * <p> * * </p> * * @author lqh * @since 2018-05-25 */@TableName('tb_student')public class Student extends Model<Student> { private static final long serialVersionUID = 1L; @TableId(value='id', type= IdType.AUTO)private Integer id;@TableField('stu_name')private String stuName;@TableField('stu_number')private String stuNumber;private Integer age; public Integer getId() {return id;} public Student setId(Integer id) {this.id = id;return this;} public String getStuName() {return stuName;} public Student setStuName(String stuName) {this.stuName = stuName;return this;} public String getStuNumber() {return stuNumber;} public Student setStuNumber(String stuNumber) {this.stuNumber = stuNumber;return this;} public Integer getAge() {return age;} public Student setAge(Integer age) {this.age = age;return this;} @Overrideprotected Serializable pkVal() {return this.id;} }

.mapper-->StudentMapper.java

package com.warrior.mapper; import com.warrior.entity.Student;import com.baomidou.mybatisplus.mapper.BaseMapper; /** * <p> * Mapper 接口 * </p> * * @author lqh * @since 2018-05-25 */public interface StudentMapper extends BaseMapper<Student> { }

mapperXml-->StudentMapper.xml(這個(gè)文件要放到src/main/resources/mapper)

<?xml version='1.0' encoding='UTF-8'?><!DOCTYPE mapper PUBLIC '-//mybatis.org//DTD Mapper 3.0//EN' 'http://mybatis.org/dtd/mybatis-3-mapper.dtd'><mapper namespace='com.warrior.mapper.StudentMapper'> <!-- 通用查詢(xún)映射結(jié)果 --><resultMap type='com.warrior.entity.Student'><id column='id' property='id' /><result column='stu_name' property='stuName' /><result column='stu_number' property='stuNumber' /><result column='age' property='age' /></resultMap> <!-- 通用查詢(xún)結(jié)果列 --> <sql id='Base_Column_List'> id, stu_name AS stuName, stu_number AS stuNumber, age </sql> </mapper>

.service-->IStudentService.java

package com.warrior.service; import com.warrior.entity.Student;import com.baomidou.mybatisplus.service.IService; /** * <p> * 服務(wù)類(lèi) * </p> * * @author lqh * @since 2018-05-25 */public interface IStudentService extends IService<Student> {}

.serviceImpl-->StudentServiceImpl.java

package com.warrior.serviceImpl; import com.warrior.entity.Student;import com.warrior.mapper.StudentMapper;import com.warrior.service.IStudentService;import com.baomidou.mybatisplus.service.impl.ServiceImpl;import org.springframework.stereotype.Service; /** * <p> * 服務(wù)實(shí)現(xiàn)類(lèi) * </p> * * @author lqh * @since 2018-05-25 */@Servicepublic class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements IStudentService {}

.controler-->StudentController.java

package com.warrior.controler; import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping; /** * <p> * 前端控制器 * </p> * * @author lqh * @since 2018-05-25 */@Controller@RequestMapping('/warrior/student')public class StudentController {}

經(jīng)過(guò)以上六步項(xiàng)目已經(jīng)搭建完成,下面就是寫(xiě)業(yè)務(wù)代碼了,只需要實(shí)現(xiàn)controller即可,下面對(duì)StudentController.java進(jìn)行修改:

package com.warrior.controler; import com.warrior.entity.Student;import com.warrior.service.IStudentService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody; /** * <p> * 前端控制器 * </p> * * @author lqh * @since 2018-05-05 */@Controller@RequestMapping('/warrior/student')public class StudentController { @Autowired IStudentService iStudentService; @RequestMapping('/hello') @ResponseBody public String hello() { //insert Student student = new Student() .setStuName('zhangsan') .setStuNumber('54') .setAge(23); boolean res = iStudentService.insert(student); return res ? 'success' : 'fail'; }}

運(yùn)行項(xiàng)目,直接訪(fǎng)問(wèn),搞定!!

項(xiàng)目github地址:https://github.com/LinQiHong66/SpringBoot_MybatisPlus.git

mybatisPlus官網(wǎng):http://mp.baomidou.com/

到此這篇關(guān)于SpringBoot+MybatisPlus+代碼生成器整合示例的文章就介紹到這了,更多相關(guān)SpringBoot MybatisPlus 代碼生成器 內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!

標(biāo)簽: Spring
相關(guān)文章:
主站蜘蛛池模板: 猪I型/II型胶原-五克隆合剂-细胞冻存培养基-北京博蕾德科技发展有限公司 | 伊卡洛斯软装首页-电动窗帘,别墅窗帘,定制窗帘,江浙沪1000+别墅窗帘案例 | 济南网站建设|济南建网站|济南网站建设公司【济南腾飞网络】【荐】 | 对夹式止回阀厂家,温州对夹式止回阀制造商--永嘉县润丰阀门有限公司 | Safety light curtain|Belt Sway Switches|Pull Rope Switch|ultrasonic flaw detector-Shandong Zhuoxin Machinery Co., Ltd | 哲力实业_专注汽车涂料汽车漆研发生产_汽车漆|修补油漆品牌厂家 长沙一级消防工程公司_智能化弱电_机电安装_亮化工程专业施工承包_湖南公共安全工程有限公司 | 沙盘模型公司_沙盘模型制作公司_建筑模型公司_工业机械模型制作厂家 | 搪瓷反应釜厂家,淄博搪瓷反应釜-淄博卓耀 | 湖州织里童装_女童男童中大童装_款式多尺码全_织里儿童网【官网】-嘉兴嘉乐网络科技有限公司 | 制冷采购电子商务平台——制冷大市场 | 无尘烘箱_洁净烤箱_真空无氧烤箱_半导体烤箱_电子防潮柜-深圳市怡和兴机电 | 地源热泵一体机,地源热泵厂家-淄博汇能环保设备有限公司 | 电脑刺绣_绣花厂家_绣花章仔_织唛厂家-[源欣刺绣]潮牌刺绣打版定制绣花加工厂家 | 楼梯定制_楼梯设计施工厂家_楼梯扶手安装制作-北京凌步楼梯 | 万烁建筑设计院-建筑设计公司加盟,设计院加盟分公司,市政设计加盟 | 锂电池砂磨机|石墨烯砂磨机|碳纳米管砂磨机-常州市奥能达机械设备有限公司 | 哈希余氯测定仪,分光光度计,ph在线监测仪,浊度测定仪,试剂-上海京灿精密机械有限公司 | 绿萝净除甲醛|深圳除甲醛公司|测甲醛怎么收费|培训机构|电影院|办公室|车内|室内除甲醛案例|原理|方法|价格立马咨询 | 南京展台搭建-南京展会设计-南京展览设计公司-南京展厅展示设计-南京汇雅展览工程有限公司 | 不锈钢钢格栅板_热浸锌钢格板_镀锌钢格栅板_钢格栅盖板-格美瑞 | 工程管道/塑料管材/pvc排水管/ppr给水管/pe双壁波纹管等品牌管材批发厂家-河南洁尔康建材 | 北京浩云律师事务所-法律顾问_企业法务_律师顾问_公司顾问 | 非小号行情 - 专业的区块链、数字藏品行情APP、金色财经官网 | 今日热点_实时热点_奇闻异事_趣闻趣事_灵异事件 - 奇闻事件 | 液压油缸-液压缸厂家价格,液压站系统-山东国立液压制造有限公司 液压油缸生产厂家-山东液压站-济南捷兴液压机电设备有限公司 | 聚合氯化铝价格_聚合氯化铝厂家_pac絮凝剂-唐达净水官网 | 稳尚教育加盟-打造高考志愿填报平台_新高考志愿填报加盟_学业生涯规划加盟 | 合肥礼品公司-合肥礼品定制-商务礼品定制公司-安徽柏榽商贸有限公司 | 隔爆型防爆端子分线箱_防爆空气开关箱|依客思 | 二手电脑回收_二手打印机回收_二手复印机回_硒鼓墨盒回收-广州益美二手电脑回收公司 | 液压油缸-液压站生产厂家-洛阳泰诺液压科技有限公司 | 医学模型生产厂家-显微手术模拟训练器-仿真手术模拟训练系统-北京医教科技 | 档案密集柜_手动密集柜_智能密集柜_内蒙古档案密集柜-盛隆柜业内蒙古密集柜直销中心 | KBX-220倾斜开关|KBW-220P/L跑偏开关|拉绳开关|DHJY-I隔爆打滑开关|溜槽堵塞开关|欠速开关|声光报警器-山东卓信有限公司 | 大连海岛旅游网>>大连旅游,大连海岛游,旅游景点攻略,海岛旅游官网 | 瑞典Blueair空气净化器租赁服务中心-专注新装修办公室除醛去异味服务! | 彩超机-黑白B超机-便携兽用B超机-多普勒彩超机价格「大为彩超」厂家 | 成都LED显示屏丨室内户外全彩led屏厂家方案报价_四川诺显科技 | 玖容气动液压设备有限公司-气液增压缸_压力机_增压机_铆接机_增压器 | 附着力促进剂-尼龙处理剂-PP处理剂-金属附着力处理剂-东莞市炅盛塑胶科技有限公司 | 聚合氯化铝-碱式氯化铝-聚合硫酸铁-聚氯化铝铁生产厂家多少钱一吨-聚丙烯酰胺价格_河南浩博净水材料有限公司 |