您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關mybatis plus代碼生成工具怎么用的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
原本想使用AutoGenerator 是 MyBatis-Plus 的官方代碼生成器 ,嘗試了一下,竟然報錯,原因可能是MyBatis-Plus和mybatis-plus-generator 的版本不一致,因為我用的MyBatis-Plus 的版本是3.42 ,但是mybatis-plus-generator的3.4.2不知道怎么了,下載不下來,只能下載3.4.1,發現運行起來老是報錯,還有一堆配置說明要看,于是自己手寫生成代碼的工具類,覺得更簡單些。分享給大家,請多多指教。
pom文件引入java-mysql 驅動依賴
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.22</version> </dependency>
單類代碼實現,復制粘貼到編輯器里,主方法運行即可。
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通用生成工具 * 可生成業務接口、mapper接口、實體類 * * @author tarzan Liu * @date 2021/4/10 19:44 */ public class MyBatisPlusTools { private static final String driver = "com.mysql.cj.jdbc.Driver";//驅動 private static final String user = "root"; //數據庫賬號 private static final String pwd = "123456"; //數據庫密碼 private static final String url = "jdbc:mysql://127.0.0.1:3306/ofcms" + "?user=" + user + "&password=" + pwd+"&useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull"; //鏈接參數 private static String tableName = "of_cms_ad"; // 數據庫表名 private static String aliasName = "cms_ad"; // 數據庫別名,可以與數據庫表名相同 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/"; // 默認生成主文件夾路徑 private static Connection getConnection = null; static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); /** * 鏈接數據庫 */ private static Connection getConnections() { try { Class.forName(driver); getConnection = DriverManager.getConnection(url); } catch (Exception e) { e.printStackTrace(); } return getConnection; } /** * 格式化默認值 */ private static String defaultValue(String value) { if (StringUtils.isNotBlank(value)) { return ";默認值:" + value; } { return ""; } } private static String getAliasName(String tableName,String prefix){ return tableName.substring(prefix.length()); } /** * 格式化數據類型 * 返回的是基本類型的包裝類 * 如果使用基本數據類型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"; } } /** * 駝峰轉換 */ private static String columnToProperty(String column) { StringBuilder result = new StringBuilder(); // 快速檢查 if (column == null || column.isEmpty()) { // 沒必要轉換 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) { // 跳過原始字符串中開頭、結尾的下換線或雙重下劃線 if (columnSplit.isEmpty()) { continue; } // 處理真正的駝峰片段 if (result.length() == 0) { // 第一個駝峰片段,全部字母都小寫 result.append(columnSplit.toLowerCase()); } else { // 其他的駝峰片段,首字母大寫 result.append(columnSplit.substring(0, 1).toUpperCase()).append(columnSplit.substring(1).toLowerCase()); } } return result.toString(); } } /** * 實體名稱轉換 */ private static String formatBeanName(String column) { StringBuilder result = new StringBuilder(); // 快速檢查 if (column == null || column.isEmpty()) { // 沒必要轉換 return ""; } else if (!column.contains("_")) { // 不含下劃線,僅將首字母大寫 return column.substring(0, 1).toUpperCase() + column.substring(1); } else { // 用下劃線將原始字符串分割 String[] columns = column.split("_"); for (String columnSplit : columns) { // 跳過原始字符串中開頭、結尾的下換線或雙重下劃線 if (columnSplit.isEmpty()) { continue; } // 處理真正的駝峰片段 result.append(columnSplit.substring(0, 1).toUpperCase()).append(columnSplit.substring(1).toLowerCase()); } return result.toString(); } } /** * 實體類字段 */ 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數據層實體類(bean.java)" + "\n狀態:成功" + "\n時間:" + 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數據持久層接口(dao.java)" + "\n狀態:成功" + "\n時間:" + 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業務層接口(service.java)" + "\n狀態:成功" + "\n時間:" + format.format(new Date()) + "\n"); } /** * 寫文件,支持中文字符,在linux redhad下測試過 * @param str 文本內容 * @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"));//注意需要轉換對應的字符集 out.close(); } catch (Exception e) { e.printStackTrace(); } } //一次生產所有表 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_"); //實體 getBean(tableName,aliasName); //dao層接口 getMapper(tableName,aliasName); //業務類接口 getService(tableName,aliasName); } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { // tableNames(); //實體 getBean(tableName,aliasName); //mapper接口 getMapper(tableName,aliasName); //業務類接口 getService(tableName,aliasName); } }
生成文件截圖
實體
mapper
service
感謝各位的閱讀!關于“mybatis plus代碼生成工具怎么用”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。