日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

MyBatisPlus自动生成代码springboot+mybatis+mysql 以及动态sql生成方法(测试可用版)

發(fā)布時間:2025/3/15 45 豆豆
生活随笔 收集整理的這篇文章主要介紹了 MyBatisPlus自动生成代码springboot+mybatis+mysql 以及动态sql生成方法(测试可用版) 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

用了一段時間的springboot,想著百度一下自動生成代碼的方式,包括后面如何生成動態(tài)sql方法的方式。
摸索了幾天,整理一下:
**

1 自動生成代碼方式:com.baomidou.mybatisplus

**

mvn配置:

<!--mybatis-plus--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.0.6</version></dependency>

創(chuàng)建包路徑:com.cbe.generator

在com.cbe.generator下創(chuàng)建CodeGenerator類:
一言不合就上代碼

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException; import com.baomidou.mybatisplus.core.toolkit.StringPool; import com.baomidou.mybatisplus.core.toolkit.StringUtils; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.InjectionConfig; import com.baomidou.mybatisplus.generator.config.*; import com.baomidou.mybatisplus.generator.config.po.TableInfo; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;import java.util.ArrayList; import java.util.List; import java.util.Scanner;// 演示例子,執(zhí)行 main 方法控制臺輸入模塊表名回車自動生成對應(yīng)項目目錄中 public class CodeGenerator {/*** <p>* 讀取控制臺內(nèi)容* </p>*/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();//當(dāng)前工程路徑String projectPath = System.getProperty("user.dir"); // System.out.println(projectPath);gc.setOutputDir(projectPath + "/src/main/java");//生成文件的輸出目錄【默認 D 盤根目錄】gc.setAuthor("liuyuzhu");//開發(fā)人員gc.setOpen(false);//是否打開輸出目錄gc.setFileOverride(true);// 是否覆蓋已有同名文件,默認是falsegc.setActiveRecord(true);// 開啟 ActiveRecord 模式,默認是falsegc.setEnableCache(false);// 是否在xml中添加二級緩存配置,默認是falsegc.setBaseResultMap(true);// 開啟 BaseResultMap,默認是falsegc.setBaseColumnList(true);// 開啟 baseColumnList,默認是false/** 各層文件名稱方式,例如: %sAction 生成 UserAction* %s 為占位符,注意 %s 會自動填充表實體屬性!*///gc.setMapperName("%sDao");//默認UserMapper.xml//gc.setXmlName("%sDao");//默認UserMapper.xml//gc.setServiceName("MP%sService");//默認IUserService.java//gc.setServiceImplName("%sServiceDiy");//默認UserServiceImpl.java//gc.setControllerName("%sAction");//默認UserController.javampg.setGlobalConfig(gc);// 數(shù)據(jù)源配置DataSourceConfig dsc = new DataSourceConfig();dsc.setUrl("jdbc:mysql://x.x.x.x:3306/xxxx?useUnicode=true&useSSL=false&characterEncoding=utf8");//dsc.setSchemaName("public");//PostgreSQL schemaNamedsc.setDriverName("com.mysql.jdbc.Driver");dsc.setUsername("xxxxxx");dsc.setPassword("xxxxx");mpg.setDataSource(dsc);// 包配置PackageConfig pc = new PackageConfig();pc.setModuleName(scanner("模塊名"));//父包模塊名,默認null//父包名。如果為空,將下面子包名必須寫全部, 否則就只需寫子包名pc.setParent("com.cbe");//默認com.baomidou//pc.setController("liuxzhController");//默認controller//pc.setService("liuxzhService");//默認service//pc.setServiceImpl("liuxzhService.impl");//默認service.impl//pc.setEntity("liuxzhEntity");//默認entity//pc.setMapper("liuxzhMapper");//默認mapper//pc.setXml("liuxzhMapper.xml");//默認mapper.xmlmpg.setPackageInfo(pc);// 自定義配置InjectionConfig cfg = new InjectionConfig() {@Overridepublic void initMap() {// to do nothing}};// 如果模板引擎是 freemarkerString templatePath = "/templates/mapper.xml.ftl";// 如果模板引擎是 velocity // String templatePath = "/templates/mapper.xml.vm";// 自定義輸出配置List<FileOutConfig> focList = new ArrayList<>();// 自定義配置會被優(yōu)先輸出focList.add(new FileOutConfig(templatePath) {@Overridepublic String outputFile(TableInfo tableInfo) {// 自定義輸出文件名return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;}});cfg.setFileOutConfigList(focList);mpg.setCfg(cfg);// 配置模板TemplateConfig templateConfig = new TemplateConfig();// 配置自定義輸出模板// templateConfig.setEntity();// templateConfig.setService();// templateConfig.setController();templateConfig.setXml(null);mpg.setTemplate(templateConfig);// 策略配置StrategyConfig strategy = new StrategyConfig();//數(shù)據(jù)庫表映射到實體的命名策略,默認:不做任何改變,原樣輸出strategy.setNaming(NamingStrategy.underline_to_camel);//數(shù)據(jù)庫表字段映射到實體的命名策略,未指定按照 naming 執(zhí)行strategy.setColumnNaming(NamingStrategy.underline_to_camel);//【實體】是否為lombok模型(默認 false)//strategy.setEntityLombokModel(true);//生成@RestController 控制器strategy.setRestControllerStyle(true);//自定義繼承的Controller類全稱,帶包名//strategy.setSuperControllerClass("com.mybatisplus.demo.common.BaseController");//strategy.setSuperServiceClass();//strategy.setSuperServiceImplClass();//strategy.setSuperMapperClass("com.mybatisplus.demo.common.BaseMapper");//strategy.setSuperEntityClass("com.mybatisplus.demo.common.BaseEntity");//自定義繼承的Entity類全稱,帶包名strategy.setInclude(scanner("表名"));//表明String數(shù)組strategy.setSuperEntityColumns("id");// 駝峰轉(zhuǎn)連字符:// @RequestMapping("/managerUserActionHistory")-->@RequestMapping("/manager-user-action-history")strategy.setControllerMappingHyphenStyle(true);strategy.setTablePrefix(pc.getModuleName() + "_");//表前綴mpg.setStrategy(strategy);//數(shù)據(jù)庫表配置mpg.setTemplateEngine(new FreemarkerTemplateEngine());// 選擇 freemarker 引擎,默認 Veloctiy//生成代碼mpg.execute();}}

執(zhí)行方法如下:執(zhí)行main方法
輸入模塊包名test,回車;在輸入表名test_case;之后回車就直接生成了代碼了。前提需要建好表。

到這里并沒有結(jié)束:
生成類似的結(jié)構(gòu)如下:


其中mapper包中需要給相關(guān)Mapper類添加注解@Mapper,給service和impl類添加注解 @Service。這樣便可以不報錯了。

2,關(guān)于注入動態(tài)代碼模塊:
注明一下:本人不喜歡配置xml,能注解的都注解。個人喜好而已。
首先,完成上述工作后通用的一些增刪改查都是有的。此處生成的是有額外需要的sql;
下面為在mapper接口層注入動態(tài)sql,有些sql可以直接寫完注入,有些則需要配置Provider單獨生成。SelectProvider,UpdateProvider等。

@Mapper public interface TestWorksheetMapper extends BaseMapper<TestWorksheet> {@SelectProvider(method = "selectByTaskNoAppName",type = WorksheetProvider.class)int selectByTaskNoAppName(@Param("taskNo") String taskNo,@Param("appName") String appName);@UpdateProvider(method = "updateByTaskNoAndAppName", type = WorksheetProvider.class)Boolean updateByTaskNoAndAppName( TestWorksheet sheet,String taskNo,String appName);@Select("SELECT addAppTime, taskNo,taskName,appName, STATUS,genbranchUser, testersStr,bugsNum, producerStr FROM TEST_WORKSHEET WHERE status not in ('合并主干完成','作廢') ORDER BY addAppTime DESC ;")List<TestWorksheet> queryWorkSheetUnDone();@Select("SELECT addAppTime, taskNo,taskName,appName, STATUS,genbranchUser, testersStr,bugsNum, producerStr FROM TEST_WORKSHEET WHERE status ='合并主干完成' and status !='作廢' ORDER BY addAppTime DESC limit 20;")List<TestWorksheet> queryWorkSheetDone();}

method = “updateByTaskNoAndAppName”, type = WorksheetProvider.class
method 的值 對應(yīng)WorksheetProvider 類中的方法名。
接下來我們看WorksheetProvider類;
以最復(fù)雜的update為例:

import org.apache.ibatis.jdbc.SQL;import com.cbe.worksheet.entity.TestWorksheet;public class WorksheetProvider {public String selectByTaskNoAppName(String taskNo, String appName) {String sql = "select count(*) from test_worksheet where taskNo='" + taskNo + "'" + " and appName='" + appName+ "' and status!='作廢';";return sql;}// 根據(jù)工單號應(yīng)用名更新數(shù)據(jù)public String updateByTaskNoAndAppName(TestWorksheet sheet, String taskNo, String appName) { // System.out.println(sheet.toString());String sql = new SQL() {{UPDATE("test_worksheet");if(sheet.getAddAppTime() != null){SET("addAppTime='"+sheet.getAddAppTime()+"'"); }if(sheet.getPtype() != null){SET("ptype='"+sheet.getPtype()+"'"); }if(sheet.getTeamDesc() != null){SET("teamDesc='"+sheet.getTeamDesc()+"'"); }if(sheet.getCasesNum() != null){SET("casesNum='"+sheet.getCasesNum()+"'"); }if(sheet.getExpectedOnlineTime() != null){SET("expectedOnlineTime='"+sheet.getExpectedOnlineTime()+"'"); }if(sheet.getMaoyanNum() != null){SET("maoyanNum='"+sheet.getMaoyanNum()+"'"); }if(sheet.getTaskNo() != null){SET("taskNo='"+sheet.getTaskNo()+"'"); }if(sheet.getActualOnlineTime() != null){SET("actualOnlineTime='"+sheet.getActualOnlineTime()+"'"); }if(sheet.getExpectedTestDoneTime() != null){SET("expectedTestDoneTime='"+sheet.getExpectedTestDoneTime()+"'"); }if(sheet.getMergeTime() != null){SET("mergeTime='"+sheet.getMergeTime()+"'"); }if(sheet.getTestNum() != null){SET("testNum='"+sheet.getTestNum()+"'"); }if(sheet.getExpectedPutTestTime() != null){SET("expectedPutTestTime='"+sheet.getExpectedPutTestTime()+"'"); }if(sheet.getPname() != null){SET("pname='"+sheet.getPname()+"'"); }if(sheet.getAppName() != null){SET("appName='"+sheet.getAppName()+"'"); }if(sheet.getGenbranchTime() != null){SET("genbranchTime='"+sheet.getGenbranchTime()+"'"); }if(sheet.getGenbranchUser() != null){SET("genbranchUser='"+sheet.getGenbranchUser()+"'"); }if(sheet.getPutMergeTime() != null){SET("putMergeTime='"+sheet.getPutMergeTime()+"'"); }if(sheet.getTestingTime() != null){SET("testingTime='"+sheet.getTestingTime()+"'"); }if(sheet.getRqtId() != null){SET("rqtId='"+sheet.getRqtId()+"'"); }if(sheet.getTestersStr() != null){SET("testersStr='"+sheet.getTestersStr()+"'"); }if(sheet.getBugsNum() != null){SET("bugsNum='"+sheet.getBugsNum()+"'"); }if(sheet.getTestWorkLoad() != null){SET("testWorkLoad='"+sheet.getTestWorkLoad()+"'"); }if(sheet.getProducerStr() != null){SET("producerStr='"+sheet.getProducerStr()+"'"); }if(sheet.getInTime() != null){SET("inTime='"+sheet.getInTime()+"'"); }if(sheet.getDevelopersStr() != null){SET("developersStr='"+sheet.getDevelopersStr()+"'"); }if(sheet.getActualPutTestTime() != null){SET("actualPutTestTime='"+sheet.getActualPutTestTime()+"'"); }if(sheet.getActualTestDoneTime() != null){SET("actualTestDoneTime='"+sheet.getActualTestDoneTime()+"'"); }if(sheet.getMergedTime() != null){SET("mergedTime='"+sheet.getMergedTime()+"'"); }if(sheet.getRqter() != null){SET("rqter='"+sheet.getRqter()+"'"); }if(sheet.getTaskName() != null){SET("taskName='"+sheet.getTaskName()+"'"); }if(sheet.getFixNum() != null){SET("fixNum='"+sheet.getFixNum()+"'"); }if(sheet.getStatus() != null){SET("status='"+sheet.getStatus()+"'"); }WHERE("taskNo='" + taskNo + "' and appName='" + appName+"'" );}}.toString(); // System.out.println(sql);return sql;}}

其中update部分 是自動打印生成的,只是復(fù)制過來使用。避免手工編寫。

if(sheet.getAddAppTime() != null){SET("addAppTime='"+sheet.getAddAppTime()+"'"); }

使用到的工具類如下:

public class SqlProvider {public static String upperCase(String str) {return str.substring(0, 1).toUpperCase() + str.substring(1); }static void update(String tabname){CreUpSql sql = new CreUpSql();String[][] string= sql.getFieldsNames(tabname);for (int i = 0; i < string.length; i++) {String parm = string[i][0]; // System.out.println(string[i][0]+" " +string[i][1]);System.out.println( " if(sheet.get"+upperCase(parm)+"() != null){SET(\""+parm+"='\"+sheet.get"+upperCase(parm)+"()+\"'\"); }");}} public static void main(String[] args) {update("test_case"); }

里面用到CreUpSql;

public class CreUpSql {/*** 獲取表的所有字段名稱* * @param tabname* @return*/public String[][] getFieldsNames(String tabname) {Connection conn = null;try {conn = ConnUtil.getConn();} catch (Exception e1) {// TODO Auto-generated catch blocke1.printStackTrace();}Statement stat = null;ResultSet rs = null;ResultSetMetaData data = null; // 定義ResultSetMetaData對象String[][] resultStrs = null;int coloumCount = 0;try {stat = conn.createStatement();String sql = "select * from " + tabname;rs = stat.executeQuery(sql);// 查詢數(shù)據(jù)data = rs.getMetaData();coloumCount = data.getColumnCount();resultStrs = new String[coloumCount][2];for (int i = 0; i < coloumCount; i++) {resultStrs[i][0] = data.getColumnName(i + 1);resultStrs[i][1] = data.getColumnTypeName(i + 1);}// 關(guān)閉數(shù)據(jù)庫資源if (rs != null) {rs.close();}if (conn != null) {conn.close();}} catch (SQLException e) {e.printStackTrace();}return resultStrs;}}

這里用到了ConnUtil ;

public class ConnUtil {private final static String DRIVER="com.mysql.jdbc.Driver";private final static String URL="jdbc:mysql://x.x.x.x:3306/xxxx?useUnicode=true&characterEncoding=utf-8";private final static String USERNAME="xxxx";//數(shù)據(jù)庫登錄用戶名private final static String PASSWORD="xxxxxx";//數(shù)據(jù)登錄密碼private static Connection conn;public static Connection getConn() throws Exception {try {Class.forName(DRIVER);conn=DriverManager.getConnection(URL,USERNAME ,PASSWORD);//連接數(shù)據(jù)庫} catch (Exception e) {throw new Exception("數(shù)據(jù)庫連接異常!");}return conn;//返回連接對象}//關(guān)閉數(shù)據(jù)庫連接public void CloseConnection() {if(null!=conn) {try {conn.close();//關(guān)閉連接} catch (SQLException e) {e.printStackTrace();}}}}

按著步驟就可以執(zhí)行。親測可用。有問題可以隨時聯(lián)系我;歡迎指教。

總結(jié)

以上是生活随笔為你收集整理的MyBatisPlus自动生成代码springboot+mybatis+mysql 以及动态sql生成方法(测试可用版)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。