• mybatis mapper.xml转建表语句


    从网上下载了代码,但是发现没有DDL建表语句,只能自己手动创建了,感觉太麻烦,就写了一个工具类

    将所有的mapper.xml放入到一个文件夹中,程序会自动读取生成建表语句

    依赖的jar

    
        org.dom4j
        dom4j
        2.1.4
    
    
        jaxen
        jaxen
        2.0.0
    
    
        org.jdom
        jdom
        1.1.3
    

    1. package com.example.demo;
    2. import java.io.BufferedReader;
    3. import java.io.File;
    4. import java.io.FileReader;
    5. import java.io.IOException;
    6. import java.io.StringReader;
    7. import java.util.List;
    8. import org.jdom.Document;
    9. import org.jdom.Element;
    10. import org.jdom.JDOMException;
    11. import org.jdom.input.SAXBuilder;
    12. import org.jdom.xpath.XPath;
    13. import org.springframework.util.StringUtils;
    14. import org.xml.sax.InputSource;
    15. public class Sqlmap2Table {
    16. // 默认所有的varchar都是512,可以保证满足绝大多数的字段
    17. private static final String DEFAULT_VARCHAR_LENGTH = "VARCHAR(256)";
    18. public static void main(String[] args) throws Exception {
    19. String sqlMapPath = "C:\\Users\\Administrator\\Downloads\\estate-public-master\\src\\main\\java\\com\\wy\\mapping";//这里指定你的sqlmap配置文件所在路径
    20. analysis(sqlMapPath);
    21. }
    22. /* 根据指定的目录进行遍历分析
    23. *
    24. * @param path
    25. * @throws IOException
    26. * @throws JDOMException
    27. */
    28. private static void analysis(String path) throws IOException, JDOMException {
    29. File filePath = new File(path);
    30. if (filePath.isDirectory() && !filePath.getName().equals(".svn")) {
    31. File[] fileList = filePath.listFiles();
    32. for (File file : fileList) {
    33. if (file.isDirectory()) {
    34. analysis(file.getAbsolutePath());
    35. } else {
    36. analysisSqlMap(file.getAbsolutePath());
    37. }
    38. }
    39. }
    40. }
    41. /**
    42. * 分析单个的sqlmap配置文件
    43. * 当然xml文件中必须设置字段类型的属性,否则无法判断字段属性
    44. * @param sqlMapFile
    45. * @throws IOException
    46. * @throws JDOMException
    47. */
    48. @SuppressWarnings("unchecked")
    49. private static void analysisSqlMap(String sqlMapFile) throws IOException, JDOMException {
    50. // System.out.println("************"+sqlMapFile);
    51. boolean isNull=false;
    52. /**
    53. * 这里要把sqlmap文件中的这一行去掉:
    54. *
    55. * 否则JDom根据文件创建Document对象时,会报找不到www.ibatis.com这个异常,导致渲染不成功。
    56. */
    57. String xmlString = filterRead(sqlMapFile, ");
    58. // XmlDocument doc = new XmlDocument();
    59. Document doc = getDocument(xmlString);
    60. String tableName = getTableNameByInsert(doc);
    61. List resultMap = (List) XPath.selectNodes(doc, "//resultMap");
    62. for (Element e : resultMap) {
    63. if (org.apache.commons.lang3.StringUtils.isBlank(tableName)){
    64. String alias = e.getAttributeValue("type");
    65. tableName = getTableName(doc, alias);
    66. }
    67. List children = e.getChildren();
    68. StringBuilder createTableString = new StringBuilder("create table `" + tableName + "` (\n\t");
    69. int size = 0;
    70. boolean isId = false;
    71. for (Element child : children) {
    72. String jdbcType = child.getAttributeValue("jdbcType"); //获取属性类型
    73. if(StringUtils.isEmpty(jdbcType)){
    74. isNull=true;
    75. break;
    76. }
    77. if (jdbcType.toUpperCase().equals("VARCHAR")) {
    78. jdbcType = DEFAULT_VARCHAR_LENGTH;
    79. }
    80. else if (jdbcType.toUpperCase().equals("CHAR")) {
    81. jdbcType = "char(10)";
    82. }
    83. else if (jdbcType.toUpperCase().equals("BIGINT")) {
    84. jdbcType = "bigint(20)";
    85. }
    86. if (jdbcType.toUpperCase().equals("INTEGER")) {
    87. jdbcType = "int(11)";
    88. }
    89. else if (jdbcType.toUpperCase().equals("DECIMAL")) {
    90. jdbcType = "decimal(10,2)";
    91. }
    92. else if (jdbcType.toUpperCase().equals("NUMERIC")) {
    93. jdbcType = "decimal(10,2)";
    94. }
    95. if (jdbcType.toUpperCase().equals("DOUBLE")) {
    96. jdbcType = "double";
    97. }
    98. if (jdbcType.toUpperCase().equals("REAL")) {
    99. jdbcType = "double";
    100. }
    101. if (jdbcType.toUpperCase().equals("BOOLEAN")) {
    102. jdbcType = "tinyint(1)";
    103. }
    104. if (jdbcType.toUpperCase().equals("FLOAT")) {
    105. jdbcType = "float";
    106. }
    107. String columnName = child.getAttributeValue("column");
    108. createTableString.append("`").append(columnName).append("` ").append(jdbcType); //加入属性和类型
    109. if ("ID".equalsIgnoreCase(columnName)){
    110. createTableString.append(" NOT NULL AUTO_INCREMENT");
    111. isId = true;
    112. }else{
    113. createTableString.append(" DEFAULT NULL");
    114. }
    115. if (size < children.size() - 1) {
    116. createTableString.append(",\n\t");
    117. }
    118. size++;
    119. }
    120. if(isNull){
    121. break;
    122. }
    123. if (isId){
    124. createTableString.append(",\n\tPRIMARY KEY (`id`) \n");
    125. }else{
    126. createTableString.append("\n");
    127. }
    128. createTableString.append(") ENGINE=InnoDB DEFAULT CHARSET=utf8;");
    129. System.out.println(createTableString.toString().toLowerCase());
    130. }
    131. }
    132. private static String getTableNameByInsert(Document doc) throws JDOMException {
    133. List resultMap = (List) XPath.selectNodes(doc, "//insert");
    134. for (Element ele : resultMap){
    135. String text = ele.getText();
    136. //System.out.println(ele.getText());
    137. int intoIndex = text.indexOf("into");
    138. if (intoIndex > 0){
    139. String s = text.substring(intoIndex+4);
    140. intoIndex = s.indexOf("(");
    141. if (intoIndex > 0){
    142. s = s.substring(0,intoIndex);
    143. return s.trim().toLowerCase();
    144. }
    145. }
    146. }
    147. return null;
    148. }
    149. private static String getTableName(Document doc, String alias) throws JDOMException {
    150. String tableName = "";
    151. String classPath = null;
    152. // 这里的alias可能是一个别名,也可能是一个java类路径,这里我通过该alias是否有点"."这个符号来区别
    153. if (!alias.contains(".")) {// 是JAVA类
    154. // 是别名,就到配置的别名中去找
    155. Element aliasElement = (Element) XPath.selectSingleNode(doc, "//typeAlias[@alias=\"" + alias + "\"]");
    156. alias = aliasElement.getAttributeValue("type");
    157. }
    158. int lastIndex = alias.lastIndexOf(".");
    159. if (lastIndex > 0) {// 是JAVA类
    160. classPath = alias.substring(lastIndex+1);
    161. }else{
    162. classPath = alias;
    163. }
    164. // int i = classPath.lastIndexOf("DO");
    165. // 取到根据表名生成的DO名称,无“DO”两个字符
    166. //classPath = classPath.substring(0, i);
    167. char[] chars = classPath.toCharArray();
    168. boolean isFirst = Boolean.TRUE;
    169. // 生成真实的表名
    170. for (char c : chars) {
    171. if (!isFirst && c >= 65 && c <= 90) {
    172. tableName += "_";
    173. }
    174. if (isFirst) {
    175. isFirst = Boolean.FALSE;
    176. }
    177. tableName += c;
    178. }
    179. // 表名转换为大写返回
    180. return tableName.toUpperCase();
    181. }
    182. /**
    183. * 过滤性阅读
    184. *
    185. * @param filePath 文件路径
    186. * @param notIncludeLineStartWith 不包括的字符,即某行的开头是这样的字符串,则在读取的时候该行忽略
    187. * @return
    188. * @throws IOException
    189. */
    190. private static String filterRead(String filePath, String notIncludeLineStartWith) throws IOException {
    191. String result = "";
    192. FileReader fr = new FileReader(filePath);
    193. BufferedReader br = new BufferedReader(fr);
    194. String line = br.readLine();
    195. while (line != null) {
    196. if (!line.startsWith(notIncludeLineStartWith)) {
    197. result += line;
    198. }
    199. line = br.readLine();
    200. if (line != null && !line.startsWith(notIncludeLineStartWith)) {
    201. result += "\n";
    202. }
    203. }
    204. br.close();
    205. fr.close();
    206. return result;
    207. }
    208. /**
    209. * 根据XML字符串 建立JDom的Document对象
    210. *
    211. * @param xmlString XML格式的字符串
    212. * @return Document 返回建立的JDom的Document对象,建立不成功将抛出异常。
    213. * @throws IOException
    214. * @throws JDOMException
    215. */
    216. private static Document getDocument(String xmlString) throws JDOMException, IOException {
    217. // SAXBuilder builder = new SAXBuilder();
    218. // Document anotherDocument = builder.build( new StringReader(xmlString));
    219. // try {
    220. // Document doc = (Document)DocumentHelper.parseText(xmlString);
    221. // return doc;
    222. //
    223. // } catch (DocumentException e) {
    224. // e.printStackTrace();
    225. // }
    226. StringReader st = new StringReader(xmlString);
    227. InputSource is = new InputSource(st);
    228. Document doc = (new SAXBuilder()).build(is);
    229. return doc;
    230. }
    231. }

  • 相关阅读:
    让logo设计更有设计感的几个方法
    【TI毫米波雷达笔记】MMwave毫米波雷达API配置及驱动(以IWR6843AOP为例)
    JUC并发编程系列详解篇四(线程基础理论)
    vue3-admin-element框架登录如何修改?
    源码硬讲HashMap结构及数据结构转换过程(图+文)
    基于Whisper+SparkAI+Pyttsx3实现全流程免费的语音交互
    网络部分
    Netty网络框架学习笔记-19(实现一个简单RPC-1)
    js多级嵌套选中效果代码实现-vue
    [java]ArrayList 的应用--(扑克牌,杨辉三角)
  • 原文地址:https://blog.csdn.net/zhb2010zhb/article/details/132922548