org.mybatis.generator.api.dom.xml.Element Java Examples

The following examples show how to use org.mybatis.generator.api.dom.xml.Element. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AliasPlugin.java    From maven-archetype with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * getElementById: 在指定的xmlElement的一级子元素中查找id值为指定value的Element. <br/>
 *
 * @author Hongbin Yuan
 * @param xmlElement	指定的xmlElement元素  <br/>
 * @param value			查找id值为指定value的Element  <br/>
 * @return
 * @since JDK 1.6
 */
public XmlElement getElementById(XmlElement xmlElement,String value){
	if(xmlElement == null){
		return null;
	}
	if(value == null || "".equals(value.trim())){
		return xmlElement;
	}
	List<Element> elementList = xmlElement.getElements();
	if(elementList != null && elementList.size() > 0){
		for(Element e : elementList){
			if(e instanceof XmlElement){
				XmlElement eXML = (XmlElement)e;
				List<Attribute> eXMLAttrList = eXML.getAttributes();
				for(Attribute a : eXMLAttrList){
					if(a!=null && "id".equals(a.getName()) && value.equals(a.getValue())){
						return eXML;
					}
				}
			}
		}
	}
	return null;
}
 
Example #2
Source File: XmlElementGeneratorTools.java    From mybatis-generator-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * 生成
 * @param element
 * @param introspectedColumn
 * @param prefix
 * @param type               1:key,2:value,3:set
 */
private static void generateSelectiveCommColumnTo(XmlElement element, IntrospectedColumn introspectedColumn, String prefix, int type) {
    switch (type) {
        case 3:
            List<Element> incrementEles = PluginTools.getHook(IIncrementsPluginHook.class).incrementSetElementGenerated(introspectedColumn, prefix, true);
            if (!incrementEles.isEmpty()) {
                // 增量插件支持
                for (Element ele : incrementEles) {
                    element.addElement(ele);
                }
            } else {
                element.addElement(new TextElement(MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn) + " = " + MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, prefix) + ","));
            }
            break;
        case 2:
            element.addElement(new TextElement(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, prefix) + ","));
            break;
        case 1:
            element.addElement(new TextElement(MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn) + ","));
            break;
    }
}
 
Example #3
Source File: OracleSupport.java    From mybatis-generator-plus with Apache License 2.0 6 votes vote down vote up
/**
 * 在单条插入动态sql中增加查询序列,以实现oracle主键自增
 *
 * @author 吴帅
 * @parameter @param element
 * @parameter @param introspectedTable
 * @createDate 2015年9月29日 下午12:00:37
 */
@Override
public void adaptInsertSelective(XmlElement element, IntrospectedTable introspectedTable) {
    TableConfiguration tableConfiguration = introspectedTable.getTableConfiguration();
    Properties properties = tableConfiguration.getProperties();
    String incrementFieldName = properties.getProperty("incrementField");
    if (incrementFieldName != null) {// 有自增字段的配置
        List<Element> elements = element.getElements();
        XmlElement selectKey = new XmlElement("selectKey");
        selectKey.addAttribute(new Attribute("keyProperty", incrementFieldName));
        selectKey.addAttribute(new Attribute("resultType", "java.lang.Long"));
        selectKey.addAttribute(new Attribute("order", "BEFORE"));
        selectKey.addElement(new TextElement("select "));
        XmlElement includeSeq = new XmlElement("include");
        includeSeq.addAttribute(new Attribute("refid", "TABLE_SEQUENCE"));
        selectKey.addElement(includeSeq);
        selectKey.addElement(new TextElement(" from dual"));
        elements.add(0, selectKey);
    }
}
 
Example #4
Source File: RenameExampleClassAndMethodsPlugin.java    From mybatis-generator-plugins with Apache License 2.0 6 votes vote down vote up
/**
 * Remove the id columns from the sql statement. Useful when the generated update statement is trying to update an
 * id column.
 *
 * @param updates
 *            the update statements
 * @param element
 *            the element
 * @param parent
 *            the parent element
 * @param index
 *            the index of the element in the parent list
 */
void removeIdColumns(List<String> updates, Element element, XmlElement parent, int index) {
	log.debug("element type: {}", element.getClass().getSimpleName());
	log.debug("element: {}", element.getFormattedContent(0));

	if (element instanceof TextElement) {
		TextElement textElement = (TextElement) element;
		for (String update : updates) {
			if (textElement.getContent().contains(update)) {
				TextElement newElement = new TextElement(textElement.getContent().replace(update, ""));
				parent.getElements().set(index, newElement);
			}
		}
	} else if (element instanceof XmlElement) {
		XmlElement xmlElement = (XmlElement) element;
		for (int i = 0; i < xmlElement.getElements().size(); i++) {
			Element e = xmlElement.getElements().get(i);
			removeIdColumns(updates, e, xmlElement, i);
		}
	}
}
 
Example #5
Source File: RenameExampleClassAndMethodsPluginTest.java    From mybatis-generator-plugins with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldIgnoreTablesWithoutIdColumns() throws Exception {
	RenameExampleClassAndMethodsPlugin plugin = spy(this.plugin);

	// Given
	willDoNothing().given(plugin).removeIdColumns(anyListOf(String.class), any(Element.class),
			any(XmlElement.class), anyInt());
	given(introspectedTable.getPrimaryKeyColumns()).willReturn(new ArrayList<IntrospectedColumn>());

	// When
	plugin.removeIdColumns(introspectedTable, element);

	// Then
	verify(plugin, times(0)).removeIdColumns(anyListOf(String.class), any(Element.class),
			any(XmlElement.class), anyInt());
}
 
Example #6
Source File: RenameExampleClassAndMethodsPluginTest.java    From mybatis-generator-plugins with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRemoveIdUpdatesFromTextElements() throws Exception {
	String update = "alias.actual_name = #{record.someProperty,jdbcType=DOUBLE},";
	List<String> updates = new ArrayList<>();
	updates.add(update);

	List<Element> elements = new ArrayList<>();
	elements.add(textElement);

	String textContent = "some content with " + update + " and some more";

	// Given
	given(textElement.getContent()).willReturn(textContent);
	given(element.getElements()).willReturn(elements);

	// When
	plugin.removeIdColumns(updates, textElement, element, 0);

	// Then
	verify(element, times(1)).getElements();
	assertThat(elements).hasSize(1);

	TextElement newTextElement = (TextElement) elements.get(0);
	assertThat(newTextElement).isNotSameAs(textElement);
	assertThat(newTextElement.getContent()).isEqualTo("some content with  and some more");
}
 
Example #7
Source File: RenameExampleClassAndMethodsPluginTest.java    From mybatis-generator-plugins with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldProcessAllChildrenOfAnXmlElement() throws Exception {
	RenameExampleClassAndMethodsPlugin plugin = spy(this.plugin);

	List<Element> elements = new ArrayList<>();
	elements.add(textElement);

	// Given
	willDoNothing().given(plugin).removeIdColumns(anyListOf(String.class), any(Element.class),
			eq(element), anyInt());
	given(element.getElements()).willReturn(elements);

	// When
	plugin.removeIdColumns(null, element, null, -1);

	// Then
	verify(plugin, times(1)).removeIdColumns(anyListOf(String.class), eq(textElement),
			eq(element), eq(0));
}
 
Example #8
Source File: XMLMergePlugin.java    From dolphin with Apache License 2.0 6 votes vote down vote up
/**
 * 从MBG生成的DOM文档结构中找到与element代表同一节点的元素对象
 *
 * @param document generate xml dom tree
 * @param element  The dom4j element
 * @return The xml element correspond to dom4j element
 */
protected XmlElement findMatchedElementIn(Document document, org.dom4j.Element element) {
  org.dom4j.Attribute id = element.attribute("id");
  String idName = id.getName();
  String idValue = id.getValue();
  for (Element me : document.getRootElement().getElements()) {
    if (me instanceof XmlElement) {
      XmlElement xe = (XmlElement) me;
      for (Attribute ab : xe.getAttributes()) {
        if (StringUtils.equals(idName, ab.getName()) && StringUtils.equals(idValue, ab.getValue())) {
          return xe;
        }
      }
    }
  }
  return null;
}
 
Example #9
Source File: FormatTools.java    From mybatis-generator-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * 替换已有注释
 * @param commentGenerator
 * @param element
 */
public static void replaceComment(CommentGenerator commentGenerator, XmlElement element) {
    Iterator<Element> elementIterator = element.getElements().iterator();
    boolean flag = false;
    while (elementIterator.hasNext()) {
        Element ele = elementIterator.next();
        if (ele instanceof TextElement && ((TextElement) ele).getContent().matches(".*<!--.*")) {
            flag = true;
        }

        if (flag) {
            elementIterator.remove();
        }

        if (ele instanceof TextElement && ((TextElement) ele).getContent().matches(".*-->.*")) {
            flag = false;
        }
    }

    XmlElement tmpEle = new XmlElement("tmp");
    commentGenerator.addComment(tmpEle);

    for (int i = tmpEle.getElements().size() - 1; i >= 0; i--) {
        element.addElement(0, tmpEle.getElements().get(i));
    }
}
 
Example #10
Source File: IncrementPlugin.java    From mybatis-generator-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * 无Selective代码生成
 * @param xmlElement
 * @param introspectedTable
 * @param hasPrefix
 */
private void generatedWithoutSelective(XmlElement xmlElement, IntrospectedTable introspectedTable, boolean hasPrefix) {
    for (int i = 0; i < xmlElement.getElements().size(); i++) {
        Element ele = xmlElement.getElements().get(i);
        // 找到text节点且格式为 set xx = xx 或者 xx = xx
        if (ele instanceof TextElement) {
            String text = ((TextElement) ele).getContent().trim();
            if (text.matches("(^set\\s)?\\S+\\s?=.*")) {
                // 清理 set 操作
                text = text.replaceFirst("^set\\s", "").trim();
                String columnName = text.split("=")[0].trim();
                IntrospectedColumn introspectedColumn = IntrospectedTableTools.safeGetColumn(introspectedTable, columnName);
                // 查找判断是否需要进行节点替换
                if (this.supportIncrement(introspectedColumn)) {
                    xmlElement.getElements().set(i, PluginTools.getHook(IIncrementPluginHook.class).generateIncrementSet(introspectedColumn, hasPrefix ? "record." : null, text.endsWith(",")));
                }
            }
        }
    }
}
 
Example #11
Source File: IncrementPlugin.java    From mybatis-generator-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * 有Selective代码生成
 * @param element
 */
private void generatedWithSelective(XmlElement element, IntrospectedTable introspectedTable, boolean hasPrefix) {
    if (this.support()) {
        // 查找 set->if->text
        List<XmlElement> sets = XmlElementTools.findXmlElements(element, "set");
        if (sets.size() > 0) {
            List<XmlElement> ifs = XmlElementTools.findXmlElements(sets.get(0), "if");
            if (ifs.size() > 0) {
                for (XmlElement xmlElement : ifs) {
                    // 下面为if的text节点
                    List<Element> textEles = xmlElement.getElements();
                    TextElement textEle = (TextElement) textEles.get(0);
                    String[] strs = textEle.getContent().split("=");
                    String columnName = strs[0].trim();
                    IntrospectedColumn introspectedColumn = IntrospectedTableTools.safeGetColumn(introspectedTable, columnName);
                    if (this.supportIncrement(introspectedColumn)) {
                        XmlElementTools.replaceXmlElement(xmlElement, PluginTools.getHook(IIncrementPluginHook.class).generateIncrementSetSelective(introspectedColumn, hasPrefix ? "record." : null));
                    }
                }
            }
        }
    }
}
 
Example #12
Source File: IncrementsPlugin.java    From mybatis-generator-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * 有Selective代码生成
 * @param element
 */
private void generatedWithSelective(XmlElement element, IntrospectedTable introspectedTable, boolean hasPrefix) {
    if (this.support()) {
        // 查找 set->if->text
        List<XmlElement> sets = XmlElementTools.findXmlElements(element, "set");
        if (sets.size() > 0) {
            List<XmlElement> ifs = XmlElementTools.findXmlElements(sets.get(0), "if");
            if (ifs.size() > 0) {
                for (XmlElement xmlElement : ifs) {
                    // 下面为if的text节点
                    List<Element> textEles = xmlElement.getElements();
                    TextElement textEle = (TextElement) textEles.get(0);
                    String[] strs = textEle.getContent().split("=");
                    String columnName = strs[0].trim();
                    IntrospectedColumn introspectedColumn = IntrospectedTableTools.safeGetColumn(introspectedTable, columnName);
                    // 查找是否需要进行增量操作
                    List<Element> incrementEles = PluginTools.getHook(IIncrementsPluginHook.class).incrementSetElementGenerated(introspectedColumn, hasPrefix ? "record." : null, true);
                    if (!incrementEles.isEmpty()) {
                        xmlElement.getElements().clear();
                        xmlElement.getElements().addAll(incrementEles);
                    }
                }
            }
        }
    }
}
 
Example #13
Source File: RenameExampleClassAndMethodsPluginTest.java    From mybatis-generator-plugins with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void shouldRemoveIdColumnsFromUpdateStatements() throws Exception {
	RenameExampleClassAndMethodsPlugin plugin = spy(this.plugin);

	IntrospectedColumn column = new IntrospectedColumn();
	column.setActualColumnName("actual_name");
	column.setJavaProperty("someProperty");
	column.setJdbcTypeName("DOUBLE");

	List<IntrospectedColumn> columns = new ArrayList<>();
	columns.add(column);

	// Given
	willDoNothing().given(plugin).removeIdColumns(anyListOf(String.class), any(Element.class),
			any(XmlElement.class), anyInt());
	given(introspectedTable.getPrimaryKeyColumns()).willReturn(columns);
	given(tableConfiguration.getAlias()).willReturn("alias");

	// When
	plugin.removeIdColumns(introspectedTable, element);

	// Then
	ArgumentCaptor<List> updatesCaptor = ArgumentCaptor.forClass(List.class);

	verify(plugin, times(1)).removeIdColumns(updatesCaptor.capture(), eq(element),
			isNull(XmlElement.class), eq(-1));

	List<String> updates = updatesCaptor.getValue();
	assertThat(updates).hasSameSizeAs(columns);
	String update = updates.get(0);
	assertThat(update).isEqualTo("alias.actual_name = #{record.someProperty,jdbcType=DOUBLE},");
}
 
Example #14
Source File: DeleteAtPlugin.java    From S-mall-ssm with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean sqlMapExampleWhereClauseElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {

    for (Element child : element.getElements()) {
        if (child instanceof XmlElement && ((XmlElement) child).getName().equals("where")) {
            TextElement element1 = new TextElement("and deleteAt is NULL");
            ((XmlElement) child).getElements().add(element1);
            break;
        }
    }
    return true;
}
 
Example #15
Source File: XmlElementTools.java    From mybatis-generator-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * 查找指定xml节点下指定节点名称的元素
 * @param xmlElement
 * @param name
 * @return
 */
public static List<XmlElement> findXmlElements(XmlElement xmlElement, String name) {
    List<XmlElement> list = new ArrayList<>();
    List<Element> elements = xmlElement.getElements();
    for (Element ele : elements) {
        if (ele instanceof XmlElement) {
            XmlElement xmlElement1 = (XmlElement) ele;
            if (name.equalsIgnoreCase(xmlElement1.getName())) {
                list.add(xmlElement1);
            }
        }
    }
    return list;
}
 
Example #16
Source File: XmlElementTools.java    From mybatis-generator-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * 查询指定xml下所有text xml 节点
 * @param xmlElement
 * @return
 */
public static List<TextElement> findAllTextElements(XmlElement xmlElement){
    List<TextElement> textElements = new ArrayList<>();
    for (Element element : xmlElement.getElements()){
        if (element instanceof XmlElement){
            textElements.addAll(findAllTextElements((XmlElement) element));
        } else if (element instanceof TextElement){
            textElements.add((TextElement) element);
        }
    }
    return textElements;
}
 
Example #17
Source File: XmlElementTools.java    From mybatis-generator-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * 拷贝
 * @param element
 * @return
 */
public static XmlElement clone(XmlElement element) {
    XmlElement destEle = new XmlElement(element.getName());
    for (Attribute attribute : element.getAttributes()) {
        destEle.addAttribute(XmlElementTools.clone(attribute));
    }
    for (Element ele : element.getElements()) {
        if (ele instanceof XmlElement) {
            destEle.addElement(XmlElementTools.clone((XmlElement) ele));
        } else if (ele instanceof TextElement) {
            destEle.addElement(XmlElementTools.clone((TextElement) ele));
        }
    }
    return destEle;
}
 
Example #18
Source File: CommentPluginTest.java    From mybatis-generator-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * 测试配置了模板参数转换
 */
@Test
public void testGenerateWithTemplate() throws Exception {
    MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/CommentPlugin/mybatis-generator.xml");
    MyBatisGenerator myBatisGenerator = tool.generate();

    // java中的注释
    for (GeneratedJavaFile file : myBatisGenerator.getGeneratedJavaFiles()) {
        if (file.getFileName().equals("Tb.java")) {
            TopLevelClass topLevelClass = (TopLevelClass) file.getCompilationUnit();
            // addJavaFileComment
            Assert.assertEquals(topLevelClass.getFileCommentLines().get(0), "TestAddJavaFileComment:Tb:" + new SimpleDateFormat("yyyy-MM").format(new Date()));
            // addFieldComment 同时测试 if 判断和 mbg
            Field id = topLevelClass.getFields().get(0);
            Assert.assertEquals(id.getJavaDocLines().get(0), "注释1");
            Assert.assertEquals(id.getJavaDocLines().get(1), MergeConstants.NEW_ELEMENT_TAG);
            // addGeneralMethodComment
            Method cons = topLevelClass.getMethods().get(0);
            Assert.assertEquals(cons.getJavaDocLines().get(0), "addGeneralMethodComment:Tb:tb");
            // addSetterComment
            Method setter = topLevelClass.getMethods().get(5);
            Assert.assertEquals(setter.getJavaDocLines().get(0), "addSetterComment:field1:field1");
        }
    }

    // xml注释
    ObjectUtil xml = new ObjectUtil(myBatisGenerator.getGeneratedXmlFiles().get(0));
    Document doc = (Document) xml.get("document");
    List<Element> els = ((XmlElement) (doc.getRootElement().getElements().get(0))).getElements();
    String comment = ((TextElement) els.get(0)).getContent();
    Assert.assertEquals(comment, "addComment:BaseResultMap");
}
 
Example #19
Source File: SQLServerPaginationPlugin.java    From dolphin with Apache License 2.0 5 votes vote down vote up
private XmlElement buildInner(XmlElement orderBy, IntrospectedTable introspectedTable) {
  // generate order by clause, first check if user provided order by clause, if provided just use it
  // otherwise use the default primary key for order by clause
  XmlElement newOrderBy = new XmlElement("choose");
  XmlElement when = new XmlElement("when");
  when.addAttribute(new Attribute("test", "orderByClause != null"));
  for (Element e : orderBy.getElements()) {
    when.addElement(e);
  }
  newOrderBy.addElement(when);

  XmlElement otherwise = new XmlElement("otherwise");
  StringBuilder sb = new StringBuilder();
  sb.append(" order by ");
  List<IntrospectedColumn> columns = introspectedTable.getPrimaryKeyColumns();
  for (IntrospectedColumn column : columns) {
    sb.append(MyBatis3FormattingUtilities.getAliasedEscapedColumnName(column)).append(", ");
  }
  sb.setLength(sb.length() - 2);
  otherwise.addElement(new TextElement(sb.toString()));
  newOrderBy.addElement(otherwise);

  XmlElement inner = new XmlElement("if");
  inner.addAttribute(new Attribute("test", "limit != null and limit>=0 and offset != null"));
  inner.addElement(new TextElement(" , ROW_NUMBER() over ( "));
  inner.addElement(newOrderBy);
  inner.addElement(new TextElement(" ) as row_num "));
  return inner;
}
 
Example #20
Source File: SQLServerPaginationPlugin.java    From dolphin with Apache License 2.0 5 votes vote down vote up
@Override
public boolean sqlMapSelectByExampleWithoutBLOBsElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {

  XmlElement orderBy = (XmlElement) findElement(element.getElements(), "if", "test", "orderByClause != null");
  XmlElement baseColumnList = (XmlElement) findElement(element.getElements(), "include", "refid", introspectedTable.getBaseColumnListId());

  XmlElement prefix = buildPrefix(baseColumnList);
  XmlElement inner = buildInner(orderBy, introspectedTable);
  XmlElement suffix = buildSuffix(orderBy);


  List<Element> elements = element.getElements();
  List<Element> newElements = new ArrayList<>();

  newElements.add(prefix);
  for (Element e : elements) {
    if(e != orderBy) {
      newElements.add(e);
      if( e == baseColumnList){
        newElements.add(inner);
      }
    }
  }
  newElements.add(suffix);

  elements.clear();
  elements.addAll(newElements);
  return true;
}
 
Example #21
Source File: XMLMergePlugin.java    From dolphin with Apache License 2.0 5 votes vote down vote up
protected String idValue(org.dom4j.Element element) {
  org.dom4j.Attribute id = element.attribute("id");
  if (id != null) {
    return id.getValue();
  } else {
    return "";
  }
}
 
Example #22
Source File: RenameExampleClassAndMethodsPluginTest.java    From mybatis-generator-plugins with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldIgnoreOtherElementSubTypes() throws Exception {
	// Given
	Element theElement = mock(Element.class);

	// When
	plugin.removeIdColumns(null, theElement, null, -1);

	// Then
}
 
Example #23
Source File: RenameExampleClassAndMethodsPluginTest.java    From mybatis-generator-plugins with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHandleElementWithoutChildren() throws Exception {
	RenameExampleClassAndMethodsPlugin plugin = spy(this.plugin);

	// Given
	willDoNothing().given(plugin).removeIdColumns(anyListOf(String.class), any(Element.class),
			eq(element), anyInt());

	// When
	plugin.removeIdColumns(null, element, null, -1);

	// Then
	verify(plugin, times(0)).removeIdColumns(anyListOf(String.class), any(Element.class),
			eq(element), anyInt());
}
 
Example #24
Source File: AbstractXmbgPlugin.java    From dolphin with Apache License 2.0 5 votes vote down vote up
protected void doIfNullCheck(String fieldPrefix, boolean ifNullCheck, XmlElement trimElement, StringBuilder sb, IntrospectedColumn introspectedColumn) {
  Element content;
  if (ifNullCheck) {
    content = wrapIfNullCheckForJavaProperty(fieldPrefix, new TextElement(sb.toString()), introspectedColumn);
  } else {
    content = new TextElement(sb.toString());
  }
  trimElement.addElement(content);
}
 
Example #25
Source File: AbstractXmbgPlugin.java    From dolphin with Apache License 2.0 5 votes vote down vote up
protected XmlElement wrapIfNullCheckForJavaProperty(String fieldPrefix, Element content, IntrospectedColumn introspectedColumn) {
  StringBuilder sb = new StringBuilder();
  XmlElement isNotNullElement = new XmlElement("if");
  sb.setLength(0);
  sb.append(introspectedColumn.getJavaProperty(fieldPrefix));
  sb.append(" != null");
  isNotNullElement.addAttribute(new Attribute("test", sb.toString()));
  isNotNullElement.addElement(content);
  return isNotNullElement;
}
 
Example #26
Source File: XMLMergePlugin.java    From dolphin with Apache License 2.0 5 votes vote down vote up
/**
 * 重组XML元素的亲子节点,合并相邻的文本节点
 *
 * @param xe The element whose content will be reformatted
 */
protected void reformationTheElementChilds(XmlElement xe) {
  List<Element> reformationList = new ArrayList<>();
  for (Element element : xe.getElements()) {
    // 如果是XML元素节点,则直接添加
    if (element instanceof XmlElement) {
      reformationList.add(element);
    }
    if (element instanceof TextElement) {
      int lastIndex = reformationList.size() - 1;
      TextElement te = (TextElement) element;

      // 如果当前文本节点之前的一个节点也是文本节点时,将两个文本节点合并成一个替换之前的节点
      // 否则直接添加
      if (!reformationList.isEmpty() && reformationList.get(lastIndex) instanceof TextElement) {
        te = (TextElement) reformationList.get(lastIndex);
        StringBuilder sb = new StringBuilder();
        sb.append(te.getContent()).append(((TextElement) element).getContent());
        te = new TextElement(sb.toString());
        reformationList.remove(lastIndex);
      }

      reformationList.add(te);
    }
  }
  // 清空原有的子元素列表,并用重组后的子节点列表填充
  xe.getElements().clear();
  xe.getElements().addAll(reformationList);
}
 
Example #27
Source File: SQLServerPaginationPlugin.java    From dolphin with Apache License 2.0 5 votes vote down vote up
int findElementIndex(List<Element> elements, String name, String key, String value) {
  int index = -1;
  for (int i = 0; i < elements.size(); i++) {
    Element element = elements.get(i);
    if (element instanceof XmlElement) {
      XmlElement xe = (XmlElement) element;
      if (matched(xe, name, key, value)) {
        index = i;
        break;
      }
    }
  }
  return index;
}
 
Example #28
Source File: XmlElementGeneratorTools.java    From mybatis-generator-plugin with Apache License 2.0 5 votes vote down vote up
public static Element getUpdateByExampleIncludeElement(IntrospectedTable introspectedTable) {
    XmlElement ifElement = new XmlElement("if");
    ifElement.addAttribute(new Attribute("test", "_parameter != null"));

    XmlElement includeElement = new XmlElement("include");
    includeElement.addAttribute(new Attribute("refid", introspectedTable.getMyBatis3UpdateByExampleWhereClauseId()));
    ifElement.addElement(includeElement);

    return ifElement;
}
 
Example #29
Source File: MybatisGeneratorPlugin.java    From java-master with Apache License 2.0 5 votes vote down vote up
@Override
public boolean sqlMapDocumentGenerated(Document document, IntrospectedTable introspectedTable) {
    Element element = new Element() {
        @Override
        public String getFormattedContent(int indentLevel) {
            StringBuilder sb = new StringBuilder();
            OutputUtilities.xmlIndent(sb, indentLevel);
            sb.append("<!-- 此文件由 mybatis generator 生成,注意: 请勿手工改动此文件, 请使用 mybatis generator -->");
            return sb.toString();
        }
    };
    document.getRootElement().addElement(0, element);
    return super.sqlMapDocumentGenerated(document, introspectedTable);
}
 
Example #30
Source File: IncrementsPlugin.java    From mybatis-generator-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * 无Selective代码生成
 * @param xmlElement
 * @param introspectedTable
 * @param hasPrefix
 */
private void generatedWithoutSelective(XmlElement xmlElement, IntrospectedTable introspectedTable, boolean hasPrefix) {
    if (this.support()) {
        List<Element> newEles = new ArrayList<>();
        for (Element ele : xmlElement.getElements()) {
            // 找到text节点且格式为 set xx = xx 或者 xx = xx
            if (ele instanceof TextElement) {
                String text = ((TextElement) ele).getContent().trim();
                if (text.matches("(^set\\s)?\\S+\\s?=.*")) {
                    // 清理 set 操作
                    text = text.replaceFirst("^set\\s", "").trim();
                    String columnName = text.split("=")[0].trim();
                    IntrospectedColumn introspectedColumn = IntrospectedTableTools.safeGetColumn(introspectedTable, columnName);
                    // 查找判断是否需要进行节点替换
                    List<Element> incrementEles = PluginTools.getHook(IIncrementsPluginHook.class).incrementSetElementGenerated(introspectedColumn, hasPrefix ? "record." : null, text.endsWith(","));
                    if (!incrementEles.isEmpty()) {
                        newEles.addAll(incrementEles);

                        continue;
                    }
                }
            }
            newEles.add(ele);
        }

        // 替换节点
        xmlElement.getElements().clear();
        xmlElement.getElements().addAll(newEles);
    }
}