飞道的博客

mybatis plus代码生成工具,可生成业务接口、mapper接口、实体类

250人阅读  评论(0)

前言:

原本想使用AutoGenerator 是 MyBatis-Plus 的官方代码生成器 ,尝试了一下,竟然报错,原因可能是MyBatis-Plus和mybatis-plus-generator 的版本不一致,因为我用的MyBatis-Plus 的版本是3.42 ,但是mybatis-plus-generator的3.4.2不知道怎么了,下载不下来,只能下载3.4.1,发现运行起来老是报错,还有一堆配置说明要看,于是自己手写生成代码的工具类,觉得更简单些。分享给大家,请多多指教。

pom文件引入java-mysql 驱动依赖 


  
  1. <dependency>
  2. <groupId>mysql </groupId>
  3. <artifactId>mysql-connector-java </artifactId>
  4. <version>8.0.22 </version>
  5. </dependency>

 

单类代码实现,复制粘贴到编辑器里,主方法运行即可。 


  
  1. import org.apache.commons.lang3.StringUtils;
  2. import java.io.File;
  3. import java.io.FileOutputStream;
  4. import java.sql.Connection;
  5. import java.sql.DatabaseMetaData;
  6. import java.sql.DriverManager;
  7. import java.sql.ResultSet;
  8. import java.text.SimpleDateFormat;
  9. import java.util.Date;
  10. /**
  11. * mybatis plus通用生成工具
  12. * 可生成业务接口、mapper接口、实体类
  13. *
  14. * @author tarzan Liu
  15. * @date 2021/4/10 19:44
  16. */
  17. public class MyBatisPlusTools {
  18. private static final String driver = "com.mysql.cj.jdbc.Driver"; //驱动
  19. private static final String user = "root"; //数据库账号
  20. private static final String pwd = "123456"; //数据库密码
  21. private static final String url = "jdbc:mysql://127.0.0.1:3306/ofcms" + "?user=" + user + "&password=" + pwd+ "&useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull"; //链接参数
  22. private static String tableName = "of_cms_ad"; // 数据库表名
  23. private static String aliasName = "cms_ad"; // 数据库别名,可以与数据库表名相同
  24. private static final String packagePath = "com/tarzan/cms"; //mapper.xml命名空间路径
  25. private static final String packageName = "com.tarzan.cms"; //mapper.xml命名空间路径
  26. private static final String author = "tarzan"; // 作者
  27. private static final String rootPathName = "src/main/java/"; // 默认生成主文件夹路径
  28. private static Connection getConnection = null;
  29. static SimpleDateFormat format = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
  30. /**
  31. * 链接数据库
  32. */
  33. private static Connection getConnections() {
  34. try {
  35. Class.forName(driver);
  36. getConnection = DriverManager.getConnection(url);
  37. } catch ( Exception e) {
  38. e.printStackTrace();
  39. }
  40. return getConnection;
  41. }
  42. /**
  43. * 格式化默认值
  44. */
  45. private static String defaultValue( String value) {
  46. if (StringUtils.isNotBlank(value)) {
  47. return ";默认值:" + value;
  48. }
  49. {
  50. return "";
  51. }
  52. }
  53. private static String getAliasName( String tableName, String prefix){
  54. return tableName.substring(prefix.length());
  55. }
  56. /**
  57. * 格式化数据类型
  58. * 返回的是基本类型的包装类
  59. * 如果使用基本数据类型long
  60. */
  61. private static String formatType( String typeValue) {
  62. if ( "bit".equalsIgnoreCase(typeValue)) {
  63. return "Boolean";
  64. }
  65. else if (
  66. typeValue.equalsIgnoreCase( "int") || typeValue.equalsIgnoreCase( "int unsigned")
  67. || typeValue.equalsIgnoreCase( "tinyint") || typeValue.equalsIgnoreCase( "tinyint unsigned")
  68. || typeValue.equalsIgnoreCase( "smallint") || typeValue.equalsIgnoreCase( "smallint unsigned")
  69. || typeValue.equalsIgnoreCase( "mediumint") || typeValue.equalsIgnoreCase( "mediumint unsigned")
  70. ) {
  71. return "Integer";
  72. } else if (typeValue.equalsIgnoreCase( "bigint") || typeValue.equalsIgnoreCase( "bigint unsigned")) {
  73. return "Long";
  74. } else if (typeValue.equalsIgnoreCase( "float") || typeValue.equalsIgnoreCase( "float unsigned")) {
  75. return "Float";
  76. } else if (typeValue.equalsIgnoreCase( "decimal") || typeValue.equalsIgnoreCase( "decimal unsigned") || typeValue.equalsIgnoreCase( "numeric") || typeValue.equalsIgnoreCase( "numeric unsigned")
  77. || typeValue.equalsIgnoreCase( "real") || typeValue.equalsIgnoreCase( "real unsigned") || typeValue.equalsIgnoreCase( "money") || typeValue.equalsIgnoreCase( "money unsigned")
  78. || typeValue.equalsIgnoreCase( "smallmoney") || typeValue.equalsIgnoreCase( "smallmoney unsigned")) {
  79. return "Double";
  80. } else if (typeValue.equalsIgnoreCase( "varchar") || typeValue.equalsIgnoreCase( "char")
  81. || typeValue.equalsIgnoreCase( "nvarchar") || typeValue.equalsIgnoreCase( "nchar")
  82. || typeValue.equalsIgnoreCase( "text")) {
  83. return "String";
  84. } else if (typeValue.equalsIgnoreCase( "datetime")) {
  85. return "Date";
  86. } else if (typeValue.equalsIgnoreCase( "image")) {
  87. return "Blod";
  88. } else {
  89. return "Long";
  90. }
  91. }
  92. /**
  93. * 驼峰转换
  94. */
  95. private static String columnToProperty( String column) {
  96. StringBuilder result = new StringBuilder();
  97. // 快速检查
  98. if (column == null || column.isEmpty()) {
  99. // 没必要转换
  100. return "";}
  101. else column =column.toLowerCase();
  102. if (!column.contains( "_")) {
  103. // 不含下划线,仅将首字母小写
  104. return column.substring( 0, 1).toLowerCase() + column.substring( 1);
  105. } else {
  106. // 用下划线将原始字符串分割
  107. String[] columns = column.split( "_");
  108. for ( String columnSplit : columns) {
  109. // 跳过原始字符串中开头、结尾的下换线或双重下划线
  110. if (columnSplit.isEmpty()) {
  111. continue;
  112. }
  113. // 处理真正的驼峰片段
  114. if (result.length() == 0) {
  115. // 第一个驼峰片段,全部字母都小写
  116. result.append(columnSplit.toLowerCase());
  117. } else {
  118. // 其他的驼峰片段,首字母大写
  119. result.append(columnSplit.substring( 0, 1).toUpperCase()).append(columnSplit.substring( 1).toLowerCase());
  120. }
  121. }
  122. return result.toString();
  123. }
  124. }
  125. /**
  126. * 实体名称转换
  127. */
  128. private static String formatBeanName( String column) {
  129. StringBuilder result = new StringBuilder();
  130. // 快速检查
  131. if (column == null || column.isEmpty()) {
  132. // 没必要转换
  133. return "";
  134. } else if (!column.contains( "_")) {
  135. // 不含下划线,仅将首字母大写
  136. return column.substring( 0, 1).toUpperCase() + column.substring( 1);
  137. } else {
  138. // 用下划线将原始字符串分割
  139. String[] columns = column.split( "_");
  140. for ( String columnSplit : columns) {
  141. // 跳过原始字符串中开头、结尾的下换线或双重下划线
  142. if (columnSplit.isEmpty()) {
  143. continue;
  144. }
  145. // 处理真正的驼峰片段
  146. result.append(columnSplit.substring( 0, 1).toUpperCase()).append(columnSplit.substring( 1).toLowerCase());
  147. }
  148. return result.toString();
  149. }
  150. }
  151. /**
  152. * 实体类字段
  153. */
  154. private static void getBean( String tableName, String aliasName) {
  155. getConnection = getConnections();
  156. StringBuilder sb = new StringBuilder();
  157. try {
  158. DatabaseMetaData dbmd = getConnection.getMetaData();
  159. ResultSet rs = dbmd.getColumns( null, "%", tableName, "%");
  160. String beanName = formatBeanName(aliasName);
  161. sb.append( "package "+packageName+ ".entity;\n\n");
  162. sb.append( "import com.baomidou.mybatisplus.annotation.TableName;\n");
  163. sb.append( "import lombok.Data;\n");
  164. int length=sb.length();
  165. boolean dateFlag= false;
  166. sb.append( " /**\n" +
  167. " * @author " + author + "\n" +
  168. " * @date "+ format.format( new Date())+ "\n" +
  169. " */\n" +
  170. "@Data\n" +
  171. "@TableName(\""+tableName+ "\")\n" +
  172. "public class "+beanName+ "Entity {\n");
  173. while (rs.next()) {
  174. if(formatType(rs.getString( "TYPE_NAME")).equals( "Date")){
  175. dateFlag= true;
  176. }
  177. sb.append( "\t//").append(rs.getString( "REMARKS")).append(defaultValue(rs.getString( "COLUMN_DEF"))).append( "\n");
  178. sb.append( "\tprivate ").append(formatType(rs.getString( "TYPE_NAME"))).append( " ").append(columnToProperty(rs.getString( "COLUMN_NAME"))).append( ";\n");
  179. }
  180. sb.append( "} ");
  181. if(dateFlag){
  182. sb.insert(length, "import java.util.Date;\n");
  183. }
  184. } catch ( Exception e) {
  185. e.printStackTrace();
  186. }
  187. write(sb.toString(), "Entity.java", "entity");
  188. System.err.println( "\n类型:JAVA数据层实体类(bean.java)" + "\n状态:成功" + "\n时间:" + format.format( new Date()) + "\n");
  189. }
  190. /**
  191. * 生成DAO层接口
  192. */
  193. private static void getMapper( String tableName, String aliasName) {
  194. StringBuilder sb = new StringBuilder();
  195. try {
  196. String beanName = formatBeanName(aliasName);
  197. sb.append( "package "+packageName+ ".mapper;\n\n");
  198. sb.append( "import com.baomidou.mybatisplus.core.mapper.BaseMapper;\n");
  199. sb.append( "import "+packageName+ ".entity."+beanName+ "Entity;\n");
  200. sb.append( "/**\n" +
  201. " * @author " + author + "\n" +
  202. " * @date "+ format.format( new Date())+ "\n" +
  203. " */\n" +
  204. "public interface "+beanName+ "Mapper extends BaseMapper<"+beanName+ "Entity>{\n" +
  205. " \n" +
  206. "}");
  207. } catch ( Exception e) {
  208. e.printStackTrace();
  209. }
  210. write(sb.toString(), "Mapper.java", "mapper");
  211. System.err.println( "\n类型:JAVA数据持久层接口(dao.java)" + "\n状态:成功" + "\n时间:" + format.format( new Date()) + "\n");
  212. }
  213. /**
  214. * 生成SERVICE层接口
  215. */
  216. private static void getService( String tableName, String aliasName) {
  217. StringBuilder sb = new StringBuilder();
  218. try {
  219. String beanName = formatBeanName(aliasName);
  220. sb.append( "package "+packageName+ ".service;\n\n");
  221. sb.append( "import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;\n");
  222. sb.append( "import org.springframework.stereotype.Service;\n");
  223. sb.append( "import "+packageName+ ".mapper."+beanName+ "Mapper;\n");
  224. sb.append( "import "+packageName+ ".entity."+beanName+ "Entity;\n");
  225. sb.append( "/**\n" +
  226. " * @author " + author + "\n" +
  227. " * @date "+ format.format( new Date())+ "\n" +
  228. " */\n" +
  229. "@Service\n" +
  230. "public class "+beanName+ "Service extends ServiceImpl<"+beanName+ "Mapper, "+beanName+ "Entity>{\n" +
  231. "\n" +
  232. "}");
  233. } catch ( Exception e) {
  234. e.printStackTrace();
  235. }
  236. write(sb.toString(), "Service.java", "service");
  237. System.err.println( "\n类型:JAVA业务层接口(service.java)" + "\n状态:成功" + "\n时间:" + format.format( new Date()) + "\n");
  238. }
  239. /**
  240. * 写文件,支持中文字符,在linux redhad下测试过
  241. * @param str 文本内容
  242. * @param name 文本名称
  243. * */
  244. private static void write( String str, String name, String type) {
  245. try {
  246. File dir = new File(rootPathName +packagePath+ "/" + type);
  247. dir.mkdirs();
  248. String path = dir.getPath() + "/" + formatBeanName(aliasName)+name;
  249. File file = new File(path);
  250. if (!file.exists())
  251. file.createNewFile();
  252. FileOutputStream out = new FileOutputStream(file, false); //如果追加方式用true
  253. StringBuilder sb = new StringBuilder();
  254. sb.append(str + "\n");
  255. out.write(sb.toString().getBytes( "utf-8")); //注意需要转换对应的字符集
  256. out.close();
  257. } catch ( Exception e) {
  258. e.printStackTrace();
  259. }
  260. }
  261. //一次生产所有表
  262. private static void tableNames() {
  263. getConnection = getConnections();
  264. try {
  265. DatabaseMetaData dbmd = getConnection.getMetaData();
  266. ResultSet rs = dbmd.getTables(getConnection.getCatalog(), null, null, new String[] { "TABLE" });
  267. while (rs.next()) {
  268. tableName=rs.getString( "TABLE_NAME");
  269. aliasName=getAliasName(tableName, "of_");
  270. //实体
  271. getBean(tableName,aliasName);
  272. //dao层接口
  273. getMapper(tableName,aliasName);
  274. //业务类接口
  275. getService(tableName,aliasName);
  276. }
  277. } catch ( Exception e) {
  278. e.printStackTrace();
  279. }
  280. }
  281. public static void main( String[] args) {
  282. // tableNames();
  283. //实体
  284. getBean(tableName,aliasName);
  285. //mapper接口
  286. getMapper(tableName,aliasName);
  287. //业务类接口
  288. getService(tableName,aliasName);
  289. }
  290. }

生成文件截图

实体

 

mapper

service


转载:https://blog.csdn.net/weixin_40986713/article/details/115655201
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场