您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關(guān)mybatis plus代碼生成工具怎么用的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過(guò)來(lái)看看吧。
原本想使用AutoGenerator 是 MyBatis-Plus 的官方代碼生成器 ,嘗試了一下,竟然報(bào)錯(cuò),原因可能是MyBatis-Plus和mybatis-plus-generator 的版本不一致,因?yàn)槲矣玫腗yBatis-Plus 的版本是3.42 ,但是mybatis-plus-generator的3.4.2不知道怎么了,下載不下來(lái),只能下載3.4.1,發(fā)現(xiàn)運(yùn)行起來(lái)老是報(bào)錯(cuò),還有一堆配置說(shuō)明要看,于是自己手寫生成代碼的工具類,覺得更簡(jiǎn)單些。分享給大家,請(qǐng)多多指教。
pom文件引入java-mysql 驅(qū)動(dòng)依賴
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.22</version> </dependency>
單類代碼實(shí)現(xiàn),復(fù)制粘貼到編輯器里,主方法運(yùn)行即可。
import org.apache.commons.lang3.StringUtils; import java.io.File; import java.io.FileOutputStream; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ResultSet; import java.text.SimpleDateFormat; import java.util.Date; /** * mybatis plus通用生成工具 * 可生成業(yè)務(wù)接口、mapper接口、實(shí)體類 * * @author tarzan Liu * @date 2021/4/10 19:44 */ public class MyBatisPlusTools { private static final String driver = "com.mysql.cj.jdbc.Driver";//驅(qū)動(dòng) private static final String user = "root"; //數(shù)據(jù)庫(kù)賬號(hào) private static final String pwd = "123456"; //數(shù)據(jù)庫(kù)密碼 private static final String url = "jdbc:mysql://127.0.0.1:3306/ofcms" + "?user=" + user + "&password=" + pwd+"&useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull"; //鏈接參數(shù) private static String tableName = "of_cms_ad"; // 數(shù)據(jù)庫(kù)表名 private static String aliasName = "cms_ad"; // 數(shù)據(jù)庫(kù)別名,可以與數(shù)據(jù)庫(kù)表名相同 private static final String packagePath = "com/tarzan/cms"; //mapper.xml命名空間路徑 private static final String packageName = "com.tarzan.cms"; //mapper.xml命名空間路徑 private static final String author = "tarzan"; // 作者 private static final String rootPathName = "src/main/java/"; // 默認(rèn)生成主文件夾路徑 private static Connection getConnection = null; static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); /** * 鏈接數(shù)據(jù)庫(kù) */ private static Connection getConnections() { try { Class.forName(driver); getConnection = DriverManager.getConnection(url); } catch (Exception e) { e.printStackTrace(); } return getConnection; } /** * 格式化默認(rèn)值 */ private static String defaultValue(String value) { if (StringUtils.isNotBlank(value)) { return ";默認(rèn)值:" + value; } { return ""; } } private static String getAliasName(String tableName,String prefix){ return tableName.substring(prefix.length()); } /** * 格式化數(shù)據(jù)類型 * 返回的是基本類型的包裝類 * 如果使用基本數(shù)據(jù)類型long */ private static String formatType(String typeValue) { if ("bit".equalsIgnoreCase(typeValue)) { return "Boolean"; } else if ( typeValue.equalsIgnoreCase("int") || typeValue.equalsIgnoreCase("int unsigned") || typeValue.equalsIgnoreCase("tinyint") || typeValue.equalsIgnoreCase("tinyint unsigned") || typeValue.equalsIgnoreCase("smallint") || typeValue.equalsIgnoreCase("smallint unsigned") || typeValue.equalsIgnoreCase("mediumint") || typeValue.equalsIgnoreCase("mediumint unsigned") ) { return "Integer"; } else if (typeValue.equalsIgnoreCase("bigint") || typeValue.equalsIgnoreCase("bigint unsigned")) { return "Long"; } else if (typeValue.equalsIgnoreCase("float") || typeValue.equalsIgnoreCase("float unsigned")) { return "Float"; } else if (typeValue.equalsIgnoreCase("decimal") || typeValue.equalsIgnoreCase("decimal unsigned") || typeValue.equalsIgnoreCase("numeric") || typeValue.equalsIgnoreCase("numeric unsigned") || typeValue.equalsIgnoreCase("real") || typeValue.equalsIgnoreCase("real unsigned") || typeValue.equalsIgnoreCase("money") || typeValue.equalsIgnoreCase("money unsigned") || typeValue.equalsIgnoreCase("smallmoney") || typeValue.equalsIgnoreCase("smallmoney unsigned")) { return "Double"; } else if (typeValue.equalsIgnoreCase("varchar") || typeValue.equalsIgnoreCase("char") || typeValue.equalsIgnoreCase("nvarchar") || typeValue.equalsIgnoreCase("nchar") || typeValue.equalsIgnoreCase("text")) { return "String"; } else if (typeValue.equalsIgnoreCase("datetime")) { return "Date"; } else if (typeValue.equalsIgnoreCase("image")) { return "Blod"; } else { return "Long"; } } /** * 駝峰轉(zhuǎn)換 */ private static String columnToProperty(String column) { StringBuilder result = new StringBuilder(); // 快速檢查 if (column == null || column.isEmpty()) { // 沒(méi)必要轉(zhuǎn)換 return "";} else column =column.toLowerCase(); if (!column.contains("_")) { // 不含下劃線,僅將首字母小寫 return column.substring(0, 1).toLowerCase() + column.substring(1); } else { // 用下劃線將原始字符串分割 String[] columns = column.split("_"); for (String columnSplit : columns) { // 跳過(guò)原始字符串中開頭、結(jié)尾的下?lián)Q線或雙重下劃線 if (columnSplit.isEmpty()) { continue; } // 處理真正的駝峰片段 if (result.length() == 0) { // 第一個(gè)駝峰片段,全部字母都小寫 result.append(columnSplit.toLowerCase()); } else { // 其他的駝峰片段,首字母大寫 result.append(columnSplit.substring(0, 1).toUpperCase()).append(columnSplit.substring(1).toLowerCase()); } } return result.toString(); } } /** * 實(shí)體名稱轉(zhuǎn)換 */ private static String formatBeanName(String column) { StringBuilder result = new StringBuilder(); // 快速檢查 if (column == null || column.isEmpty()) { // 沒(méi)必要轉(zhuǎn)換 return ""; } else if (!column.contains("_")) { // 不含下劃線,僅將首字母大寫 return column.substring(0, 1).toUpperCase() + column.substring(1); } else { // 用下劃線將原始字符串分割 String[] columns = column.split("_"); for (String columnSplit : columns) { // 跳過(guò)原始字符串中開頭、結(jié)尾的下?lián)Q線或雙重下劃線 if (columnSplit.isEmpty()) { continue; } // 處理真正的駝峰片段 result.append(columnSplit.substring(0, 1).toUpperCase()).append(columnSplit.substring(1).toLowerCase()); } return result.toString(); } } /** * 實(shí)體類字段 */ private static void getBean(String tableName,String aliasName) { getConnection = getConnections(); StringBuilder sb = new StringBuilder(); try { DatabaseMetaData dbmd = getConnection.getMetaData(); ResultSet rs = dbmd.getColumns(null, "%", tableName, "%"); String beanName = formatBeanName(aliasName); sb.append("package "+packageName+".entity;\n\n"); sb.append("import com.baomidou.mybatisplus.annotation.TableName;\n"); sb.append("import lombok.Data;\n"); int length=sb.length(); boolean dateFlag=false; sb.append( " /**\n" + " * @author " + author + "\n" + " * @date "+ format.format(new Date())+"\n" + " */\n" + "@Data\n" + "@TableName(\""+tableName+"\")\n" + "public class "+beanName+"Entity {\n"); while (rs.next()) { if(formatType(rs.getString("TYPE_NAME")).equals("Date")){ dateFlag=true; } sb.append("\t//").append(rs.getString("REMARKS")).append(defaultValue(rs.getString("COLUMN_DEF"))).append("\n"); sb.append("\tprivate ").append(formatType(rs.getString("TYPE_NAME"))).append(" ").append(columnToProperty(rs.getString("COLUMN_NAME"))).append(";\n"); } sb.append("} "); if(dateFlag){ sb.insert(length, "import java.util.Date;\n"); } } catch (Exception e) { e.printStackTrace(); } write(sb.toString(),"Entity.java","entity"); System.err.println("\n類型:JAVA數(shù)據(jù)層實(shí)體類(bean.java)" + "\n狀態(tài):成功" + "\n時(shí)間:" + format.format(new Date()) + "\n"); } /** * 生成DAO層接口 */ private static void getMapper(String tableName,String aliasName) { StringBuilder sb = new StringBuilder(); try { String beanName = formatBeanName(aliasName); sb.append("package "+packageName+".mapper;\n\n"); sb.append("import com.baomidou.mybatisplus.core.mapper.BaseMapper;\n"); sb.append("import "+packageName+".entity."+beanName+"Entity;\n"); sb.append( "/**\n" + " * @author " + author + "\n" + " * @date "+ format.format(new Date())+"\n" + " */\n" + "public interface "+beanName+"Mapper extends BaseMapper<"+beanName+"Entity>{\n" + " \n" + "}"); } catch (Exception e) { e.printStackTrace(); } write(sb.toString(),"Mapper.java","mapper"); System.err.println("\n類型:JAVA數(shù)據(jù)持久層接口(dao.java)" + "\n狀態(tài):成功" + "\n時(shí)間:" + format.format(new Date()) + "\n"); } /** * 生成SERVICE層接口 */ private static void getService(String tableName,String aliasName) { StringBuilder sb = new StringBuilder(); try { String beanName = formatBeanName(aliasName); sb.append("package "+packageName+".service;\n\n"); sb.append("import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;\n"); sb.append("import org.springframework.stereotype.Service;\n"); sb.append("import "+packageName+".mapper."+beanName+"Mapper;\n"); sb.append("import "+packageName+".entity."+beanName+"Entity;\n"); sb.append( "/**\n" + " * @author " + author + "\n" + " * @date "+ format.format(new Date())+"\n" + " */\n" + "@Service\n" + "public class "+beanName+"Service extends ServiceImpl<"+beanName+"Mapper, "+beanName+"Entity>{\n" + "\n" + "}"); } catch (Exception e) { e.printStackTrace(); } write(sb.toString(),"Service.java","service"); System.err.println("\n類型:JAVA業(yè)務(wù)層接口(service.java)" + "\n狀態(tài):成功" + "\n時(shí)間:" + format.format(new Date()) + "\n"); } /** * 寫文件,支持中文字符,在linux redhad下測(cè)試過(guò) * @param str 文本內(nèi)容 * @param name 文本名稱 * */ private static void write(String str, String name,String type) { try { File dir = new File(rootPathName +packagePath+ "/" + type); dir.mkdirs(); String path = dir.getPath() + "/" + formatBeanName(aliasName)+name; File file = new File(path); if (!file.exists()) file.createNewFile(); FileOutputStream out = new FileOutputStream(file, false); //如果追加方式用true StringBuilder sb = new StringBuilder(); sb.append(str + "\n"); out.write(sb.toString().getBytes("utf-8"));//注意需要轉(zhuǎn)換對(duì)應(yīng)的字符集 out.close(); } catch (Exception e) { e.printStackTrace(); } } //一次生產(chǎn)所有表 private static void tableNames() { getConnection = getConnections(); try { DatabaseMetaData dbmd = getConnection.getMetaData(); ResultSet rs = dbmd.getTables(getConnection.getCatalog(), null, null, new String[] { "TABLE" }); while (rs.next()) { tableName=rs.getString("TABLE_NAME"); aliasName=getAliasName(tableName,"of_"); //實(shí)體 getBean(tableName,aliasName); //dao層接口 getMapper(tableName,aliasName); //業(yè)務(wù)類接口 getService(tableName,aliasName); } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { // tableNames(); //實(shí)體 getBean(tableName,aliasName); //mapper接口 getMapper(tableName,aliasName); //業(yè)務(wù)類接口 getService(tableName,aliasName); } }
生成文件截圖
實(shí)體
mapper
service
感謝各位的閱讀!關(guān)于“mybatis plus代碼生成工具怎么用”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。