1. 程式人生 > >maven+mybatis+mybatis-generator+sql server 2005自動生成程式碼,加上自定義分頁外掛和批量插入更新外掛

maven+mybatis+mybatis-generator+sql server 2005自動生成程式碼,加上自定義分頁外掛和批量插入更新外掛

第一步:準備需要的jar包。由於maven只要配置pom.xml就可以從倉庫下載jar包。因此我們首先配置pom.xml。

注意com.microsoft.sqlserver需要自己加入maven倉庫的。

	<dependencies>
		......
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.2.3</version>
		</dependency>
		
		<dependency>
			<groupId>com.microsoft.sqlserver</groupId>
			<artifactId>sqljdbc4</artifactId>
			<version>4.0</version>
		</dependency>

		<dependency>
			<groupId>org.mybatis.generator</groupId>
			<artifactId>mybatis-generator-core</artifactId>
			<version>1.3.2</version>
		</dependency>
		
		......
	</dependencies>

	<build>
		......
		<plugins> 
			......
        	
        	<!-- generator外掛 -->
			<plugin>
				<groupId>org.mybatis.generator</groupId>
				<artifactId>mybatis-generator-maven-plugin</artifactId>
				<version>1.3.2</version>
				<configuration>  
					<overwrite>true</overwrite>  
					<verbose>true</verbose>
				</configuration>
				
				<dependencies>
					<dependency>
						<groupId>com.microsoft.sqlserver</groupId>
						<artifactId>sqljdbc4</artifactId>
						<version>4.0</version>
					</dependency>
					<dependency>  
						<groupId>com.montnets.edusun</groupId>
						<artifactId>mybatis-user-defined-plugin</artifactId>
						<version>0.1</version>
					</dependency>
				</dependencies>
			</plugin>
		</plugins>
	</build>

第二步:配置generatorConfig.xml檔案。在src/main/resources資料夾下新建generatorConfig.xml檔案,配置檔案如下程式碼所示。

<generatorConfiguration>
	<properties resource="datasource.properties" />  
<!--     資料庫驅動包位置 配置在pom.xml檔案中 -->
    <context id="MSSQLTables" targetRuntime="MyBatis3">
    	<plugin type="org.mybatis.generator.plugins.SerializablePlugin"></plugin>
<!--     	<plugin type="org.mybatis.generator.plugins.ToStringPlugin"></plugin>  -->
        <plugin type="com.montnets.mybatis.generator.plugins.InsertAndUpdateBatch"></plugin>
    	<!-- Pagination -->  
        <plugin type="com.montnets.mybatis.generator.plugins.PaginationPlugin">
        	<property name="pageQualifiedName" value="com.montnets.edusun.common.Page" />
			<property name="fromIndex" value="fromIndex" />
			<property name="toIndex" value="toIndex" />
			<property name="myBatisRepository" value="com.montnets.edusun.common.MyBatisRepository" />
        </plugin>
    
        <commentGenerator>
        	<!-- 是否去除自動生成的註釋 true:是 : false:否 -->  
            <property name="suppressAllComments" value="true" />
        </commentGenerator>
        
        <!-- 資料庫連結URL、使用者名稱、密碼 -->
        <jdbcConnection driverClass="${jdbc.driver}" 
        	connectionURL="${jdbc.url}" 
        	userId="${jdbc.username}" 
        	password="${jdbc.password}">
        </jdbcConnection>
        
		<!--  預設false,把JDBC DECIMAL 和 NUMERIC 型別解析為 Integer   
			true,把JDBC DECIMAL 和 NUMERIC 型別解析為java.math.BigDecimal  -->  
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>
     
        <!-- 生成模型的包名和位置 -->
        <javaModelGenerator targetPackage="com.montnets.edusun.entity.test" targetProject="./src/main/java">
            <property name="enableSubPackages" value="true" />
            <!-- 從資料庫返回的值被清理前後的空格  --> 
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!-- 生成的對映檔案包名和位置 -->
        <sqlMapGenerator targetPackage="sqlmaps.test" targetProject="./src/main/resources">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>
        <!-- 生成DAO的包名和位置 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.montnets.edusun.dao.test" targetProject="./src/main/java">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>
        <!-- 要生成那些表(更改tableName和domainObjectName就可以) -->
        <table tableName="Edu_Notice" domainObjectName="EduNotice">
        	<generatedKey column="id" sqlStatement="JDBC" identity="true"/>
        </table>
    </context>
</generatorConfiguration>

對應的datasource.properties如下所示

#sql server database settings
jdbc.driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
jdbc.url=jdbc:sqlserver://127.0.0.1:1433;DatabaseName=test
jdbc.username=sa
jdbc.password=******

第三步:執行mybatis-generator。命令:mybatis-generator:generate
詳細介紹請參照:點選開啟官網連結

-----------------------------------------------------------------------------------------------------------------------

下面介紹一下自定義的兩個外掛:InsertAndUpdateBatch和PaginationPlugin。這兩個外掛都被封裝在mybatis-user-defined-plugin.jar包中。需要在maven的倉庫中註冊該jar包,pom.xml和generatorConfig.xml裡的配置方式已經在前面有了。

InsertAndUpdateBatch: 配置後在生成程式碼時,會在介面和sqlmap檔案中生成updateBySelectiveBatch、updateBatch、insertBatch三個方法和對應的sql語句。

PaginationPlugin:配置後在生成程式碼時,會在介面和sqlmap檔案中生成countTotalData、pageQuery兩個方法和對應的sql語句。需要注意的是該外掛的四個引數,前三個引數為必需的,後一個引數為非必需的。

pageQualifiedName——分頁類的全路徑

fromIndex——分頁查詢中需要用到的起始索引名稱

toIndex——分頁查詢中需要用到的結束索引名稱

myBatisRepository——介面為mybatis提供的掃描註解類的全名。


原始碼如下:

import static org.mybatis.generator.internal.util.StringUtility.stringHasValue;
import static org.mybatis.generator.internal.util.messages.Messages.getString;

import java.util.List;

import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.Interface;
import org.mybatis.generator.api.dom.java.JavaVisibility;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.Parameter;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.Document;
import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement;

/**
 * @author 羅勇
 * @date 2013年11月6日  下午2:45:26
 */
public class PaginationPlugin extends PluginAdapter {
	
	private String pageQualifiedName;	//分頁類的全名
	private String fromIndex;			//Page物件中,查詢起始位置的屬性名稱
	private String toIndex;				//Page物件中,查詢結束位置的屬性名稱
	private String myBatisRepository;	//介面註解全名
	
	/**
	 * 驗證外掛的配置是否正確
	 */
	public boolean validate(List<String> warnings) {
		
		pageQualifiedName = properties.getProperty("pageQualifiedName");
		fromIndex = properties.getProperty("fromIndex");
		toIndex = properties.getProperty("toIndex");
		myBatisRepository = properties.getProperty("myBatisRepository");

		if (!stringHasValue(pageQualifiedName)) {
			warnings.add(getString("ValidationError.18", "PaginationPlugin", "pageQualifiedName"));
			return false;
		}
		if (!stringHasValue(fromIndex)) {
			warnings.add(getString("ValidationError.18", "PaginationPlugin", "fromIndex"));
			return false;
		}
		if (!stringHasValue(toIndex)) {
			warnings.add(getString("ValidationError.18", "PaginationPlugin", "toIndex"));
			return false;
		}
		return true;
	}
	
	/**
	 * 在介面中新增方法
	 */
	@Override
	public boolean clientGenerated(Interface interfaze, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
		String objectName = introspectedTable.getTableConfiguration().getDomainObjectName();//物件名稱

		interfaze.addImportedType(new FullyQualifiedJavaType("java.util.List"));
		interfaze.addImportedType(new FullyQualifiedJavaType(pageQualifiedName));
		
		if (stringHasValue(myBatisRepository) && myBatisRepository.contains(".")) {
			int index = myBatisRepository.lastIndexOf('.');
			interfaze.addImportedType(new FullyQualifiedJavaType(myBatisRepository));
			interfaze.addAnnotation("@" + myBatisRepository.substring(index + 1));//介面添加註解
		}
		
		Method method = new Method();//統計記錄總條數方法
		method.setName("countTotalData");
		method.setReturnType(new FullyQualifiedJavaType("int"));
		interfaze.addMethod(method);
		method = new Method();//分頁查詢方法
		method.setName("pageQuery");
		method.addParameter(new Parameter(new FullyQualifiedJavaType(pageQualifiedName), "page"));
		method.setReturnType(new FullyQualifiedJavaType("java.util.List<" + objectName + ">"));
		interfaze.addMethod(method);
		
		return super.clientGenerated(interfaze, topLevelClass, introspectedTable);
	}
	
	/**
	 * 在xml檔案中新增需要的元素
	 */
	@Override
	public boolean sqlMapDocumentGenerated(Document document, IntrospectedTable introspectedTable) {
		XmlElement parentElement = document.getRootElement();
		String tableName = introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime();//資料庫表名
		
		// 產生統計記錄數查詢
		XmlElement countTotalDataElement = new XmlElement("select");
		countTotalDataElement.addAttribute(new Attribute("id", "countTotalData"));
		countTotalDataElement.addAttribute(new Attribute("resultType", "java.lang.Integer"));
		countTotalDataElement.addElement(new TextElement("select count(1) from " + tableName));
		parentElement.addElement(countTotalDataElement);
		
		// 產生分頁查詢語句
		XmlElement pageQueryElement = new XmlElement("select");
		pageQueryElement.addAttribute(new Attribute("id", "pageQuery"));
		pageQueryElement.addAttribute(new Attribute("resultMap", "BaseResultMap"));
		pageQueryElement.addAttribute(new Attribute("parameterType", pageQualifiedName));
		XmlElement queryStart = new XmlElement("include");
		queryStart.addAttribute(new Attribute("refid", "PageQueryPrefix"));
		pageQueryElement.addElement(queryStart);
		pageQueryElement.addElement(new TextElement("select "));
		XmlElement query = new XmlElement("include");
		query.addAttribute(new Attribute("refid", "Base_Column_List"));
		pageQueryElement.addElement(query);
		pageQueryElement.addElement(new TextElement("from " + tableName));
		XmlElement queryEnd = new XmlElement("include");
		queryEnd.addAttribute(new Attribute("refid", "PageQuerySuffix"));
		pageQueryElement.addElement(queryEnd);
		parentElement.addElement(pageQueryElement);

		// 產生分頁語句前半部分
		XmlElement paginationPrefixElement = new XmlElement("sql");
		paginationPrefixElement.addAttribute(new Attribute("id", "PageQueryPrefix"));
		XmlElement pageStart = new XmlElement("if");
		pageStart.addAttribute(new Attribute("test", "fromIndex != null and toIndex != null"));
		pageStart.addElement(new TextElement("select * from (select row_number() over (order by id desc) as rownum,* from( "));
		paginationPrefixElement.addElement(pageStart);
		parentElement.addElement(paginationPrefixElement);

		// 產生分頁語句後半部分
		XmlElement paginationSuffixElement = new XmlElement("sql");
		paginationSuffixElement.addAttribute(new Attribute("id", "PageQuerySuffix"));
		XmlElement pageEnd = new XmlElement("if");
		pageEnd.addAttribute(new Attribute("test", "fromIndex != null and toIndex != null"));
		pageEnd.addElement(new TextElement("<![CDATA[ ) as t1 ) as t2 where rownum <= #{" + toIndex + "} and rownum >= #{" + fromIndex + "} ]]>"));
		paginationSuffixElement.addElement(pageEnd);
		parentElement.addElement(paginationSuffixElement);

		return super.sqlMapDocumentGenerated(document, introspectedTable);
	}
	
	/**
	 * 在Example配置為true時,在Example物件中新增get/set方法
	 */
	@Override
	public boolean modelExampleClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
		String name = "page";
		topLevelClass.addImportedType(new FullyQualifiedJavaType(pageQualifiedName));
		Field field = new Field();
		field.setVisibility(JavaVisibility.PROTECTED);
		field.setType(new FullyQualifiedJavaType(pageQualifiedName));
		field.setName(name);
		topLevelClass.addField(field);
		char c = name.charAt(0);
		String camel = Character.toUpperCase(c) + name.substring(1);
		Method method = new Method();
		method.setVisibility(JavaVisibility.PUBLIC);
		method.setName("set" + camel);
		method.addParameter(new Parameter(new FullyQualifiedJavaType(pageQualifiedName), name));
		method.addBodyLine("this." + name + "=" + name + ";");
		topLevelClass.addMethod(method);
		method = new Method();
		method.setVisibility(JavaVisibility.PUBLIC);
		method.setReturnType(new FullyQualifiedJavaType(pageQualifiedName));
		method.setName("get" + camel);
		method.addBodyLine("return " + name + ";");
		topLevelClass.addMethod(method);
		
		return super.modelExampleClassGenerated(topLevelClass, introspectedTable);
	}

	/**
	 * 在Example配置為true時,對生成的排除了大欄位Example查詢語句新增分頁語句
	 */
	@Override
	public boolean sqlMapSelectByExampleWithoutBLOBsElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {

		XmlElement pageStart = new XmlElement("include"); 
		pageStart.addAttribute(new Attribute("refid", "PageQueryPrefix"));
		element.getElements().add(0, pageStart);

		XmlElement isNotNullElement = new XmlElement("include"); 
		isNotNullElement.addAttribute(new Attribute("refid", "PageQuerySuffix"));
		element.getElements().add(isNotNullElement);

		return super.sqlMapUpdateByExampleWithoutBLOBsElementGenerated(element, introspectedTable);
	}

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.OutputUtilities;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.Interface;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.Parameter;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.Document;
import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.codegen.mybatis3.MyBatis3FormattingUtilities;

/**
 * 
 * @author 羅勇
 * @date 2013年11月19日  下午3:47:25
 */
public class InsertAndUpdateBatch extends PluginAdapter {
	
	private String item = "item";
	
	/**
	 * 驗證外掛的配置是否正確
	 */
	public boolean validate(List<String> warnings) {
		return true;
	}
	
	/**
	 * 在介面中新增方法
	 */
	@Override
	public boolean clientGenerated(Interface interfaze, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
		String objectName = introspectedTable.getTableConfiguration().getDomainObjectName();//物件名稱
		
		interfaze.addImportedType(new FullyQualifiedJavaType("java.util.List"));

		Method method = new Method();//
		method.addJavaDocLine("/**");
		method.addJavaDocLine(" * Batch update or insert. Parameters can not be more than 2100");
		method.addJavaDocLine(" * list of size not greater than 1000");
		method.addJavaDocLine(" */");
		method.setName("updateBySelectiveBatch");
		method.addParameter(new Parameter(new FullyQualifiedJavaType("java.util.List<" + objectName + ">"), "list"));
		method.setReturnType(new FullyQualifiedJavaType("void"));
		
		/*該行程式碼的作用:當commentGenerator配置為false時,介面可以生成註釋程式碼。
	              沒有意義,所以註釋,其他新加的方法已經刪除*/
		//context.getCommentGenerator().addGeneralMethodComment(method, introspectedTable);
		
		interfaze.addMethod(method);
		method = new Method();//
		method.setName("updateBatch");
		method.addParameter(new Parameter(new FullyQualifiedJavaType("java.util.List<" + objectName + ">"), "list"));
		method.setReturnType(new FullyQualifiedJavaType("void"));
		interfaze.addMethod(method);
		method = new Method();//
		method.setName("insertBatch");
		method.addParameter(new Parameter(new FullyQualifiedJavaType("java.util.List<" + objectName + ">"), "list"));
		method.setReturnType(new FullyQualifiedJavaType("void"));
		interfaze.addMethod(method);
		
		return super.clientGenerated(interfaze, topLevelClass, introspectedTable);
	}
	
	/**
	 * 在xml檔案中新增需要的元素
	 */
	@Override
	public boolean sqlMapDocumentGenerated(Document document, IntrospectedTable introspectedTable) {
		XmlElement parentElement = document.getRootElement();
		String tableName = introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime();//資料庫表名
		
		parentElement.addElement(getUpdateBatchBySelectiveElement(introspectedTable, tableName));
		
		parentElement.addElement(getUpdateBatchElement(introspectedTable, tableName));//批量更新

		parentElement.addElement(getInsertBatchElement(introspectedTable, tableName));//批量插入

		return super.sqlMapDocumentGenerated(document, introspectedTable);
	}
	
	/**
	 * 批量修改BySelective
	 * @param introspectedTable
	 * @param tableName
	 * @return
	 */
	public XmlElement getUpdateBatchBySelectiveElement(IntrospectedTable introspectedTable, String tableName) {
        XmlElement updateBatchElement = new XmlElement("update");
        updateBatchElement.addAttribute(new Attribute("id", "updateBySelectiveBatch"));
        
        XmlElement foreachElement = NewForeachElement();
		XmlElement ifElement = NewIfElement(introspectedTable.getPrimaryKeyColumns());

		/*該行程式碼的作用:當commentGenerator配置為false時,sql可以生成註釋程式碼。
		     沒有意義,所以註釋,其他新加的方法已經刪除*/
		//context.getCommentGenerator().addComment(updateBatchElement);

        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(tableName);
        ifElement.addElement(new TextElement(sb.toString()));

        XmlElement dynamicElement = new XmlElement("set");
        ifElement.addElement(dynamicElement);

        for (IntrospectedColumn introspectedColumn : introspectedTable.getNonPrimaryKeyColumns()) {
        	XmlElement isNotNullElement = new XmlElement("if");
        	isNotNullElement.addAttribute(new Attribute("test", introspectedColumn.getJavaProperty(item + ".") + " != null"));
            dynamicElement.addElement(isNotNullElement);

            sb.setLength(0);
            sb.append(MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn));
            sb.append(" = ");
            sb.append(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, item + "."));
            sb.append(',');

            isNotNullElement.addElement(new TextElement(sb.toString()));
        }

        boolean and = false;
        for (IntrospectedColumn introspectedColumn : introspectedTable.getPrimaryKeyColumns()) {
            sb.setLength(0);
            if (and) {
                sb.append("  and ");
            } else {
                sb.append("where ");
                and = true;
            }

            sb.append(MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn));
            sb.append(" = ");
            sb.append(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, item + "."));
            ifElement.addElement(new TextElement(sb.toString()));
        }
        
        foreachElement.addElement(ifElement);
        updateBatchElement.addElement(foreachElement);

        return updateBatchElement;
    }
	
	/**
	 * 批量修改
	 * @param introspectedTable
	 * @param tableName
	 * @return
	 */
	public XmlElement getUpdateBatchElement(IntrospectedTable introspectedTable, String tableName) {
		XmlElement updateBatchElement = new XmlElement("update"); 
        updateBatchElement.addAttribute(new Attribute("id", "updateBatch"));

        XmlElement foreachElement = NewForeachElement();
		XmlElement ifElement = NewIfElement(introspectedTable.getPrimaryKeyColumns());

        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(tableName);
        ifElement.addElement(new TextElement(sb.toString()));

        // set up for first column
        sb.setLength(0);
        sb.append("set "); 

        Iterator<IntrospectedColumn> iter = introspectedTable.getNonPrimaryKeyColumns().iterator();
        while (iter.hasNext()) {
            IntrospectedColumn introspectedColumn = iter.next();

            sb.append(MyBatis3FormattingUtilities.getAliasedEscapedColumnName(introspectedColumn));
            sb.append(" = ");
            sb.append(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, item + "."));

            if (iter.hasNext()) {
                sb.append(',');
            }

            ifElement.addElement(new TextElement(sb.toString()));

            // set up for the next column
            if (iter.hasNext()) {
                sb.setLength(0);
                OutputUtilities.xmlIndent(sb, 1);
            }
        }
        
        boolean and = false;
        for (IntrospectedColumn introspectedColumn : introspectedTable.getPrimaryKeyColumns()) {
            sb.setLength(0);
            if (and) {
                sb.append("  and ");
            } else {
                sb.append("where ");
                and = true;
            }

            sb.append(MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn));
            sb.append(" = ");
            sb.append(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, item + "."));
            ifElement.addElement(new TextElement(sb.toString()));
        }
        
        foreachElement.addElement(ifElement);
		updateBatchElement.addElement(foreachElement);

        return updateBatchElement;
    }
	
	/**
	 * 批量新增
	 * @param introspectedTable
	 * @param tableName
	 * @return
	 */
	public XmlElement getInsertBatchElement(IntrospectedTable introspectedTable, String tableName) {
        XmlElement insertBatchElement = new XmlElement("insert");
        insertBatchElement.addAttribute(new Attribute("id", "insertBatch"));

        XmlElement foreachElement = NewForeachElement();
        
        StringBuilder insertClause = new StringBuilder();
        StringBuilder valuesClause = new StringBuilder();

        insertClause.append("insert into "); 
        insertClause.append(tableName);
        insertClause.append(" (");

        valuesClause.append("values (");

        List<String> valuesClauses = new ArrayList<String>();
        Iterator<IntrospectedColumn> iter = introspectedTable.getAllColumns().iterator();
        while (iter.hasNext()) {
            IntrospectedColumn introspectedColumn = iter.next();
            if (introspectedColumn.isIdentity()) {
                // cannot set values on identity fields
                continue;
            }

            insertClause.append(MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn));
            valuesClause.append(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, item + "."));
            if (iter.hasNext()) {
                insertClause.append(", ");
                valuesClause.append(", ");
            }

            if (valuesClause.length() > 80) {
            	foreachElement.addElement(new TextElement(insertClause.toString()));
                insertClause.setLength(0);
                OutputUtilities.xmlIndent(insertClause, 1);

                valuesClauses.add(valuesClause.toString());
                valuesClause.setLength(0);
                OutputUtilities.xmlIndent(valuesClause, 1);
            }
        }

        insertClause.append(')');
        foreachElement.addElement(new TextElement(insertClause.toString()));

        valuesClause.append(')');
        valuesClauses.add(valuesClause.toString());

        for (String clause : valuesClauses) {
        	foreachElement.addElement(new TextElement(clause));
        }
        
        insertBatchElement.addElement(foreachElement);

        return insertBatchElement;
    }
	
	/**
	 * @return
	 */
	public XmlElement NewForeachElement(){
		XmlElement foreachElement = new XmlElement("foreach");
		foreachElement.addAttribute(new Attribute("collection", "list"));
		foreachElement.addAttribute(new Attribute("item", item));
		foreachElement.addAttribute(new Attribute("index", "index"));
		foreachElement.addAttribute(new Attribute("separator", ";"));
		return foreachElement;
	}
	
	/**
	 * @param primaryKeyColumns
	 * @return
	 */
	public XmlElement NewIfElement(List<IntrospectedColumn> primaryKeyColumns){
		StringBuilder sb = new StringBuilder();
		boolean flag = false;
		for (IntrospectedColumn introspectedColumn : primaryKeyColumns) {
			if (flag) {
				sb.append(" and ");
				sb.append(item).append(".");
				sb.append(MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn));
				sb.append(" != null");
			} else {
				sb.append(item).append(".");
				sb.append(MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn));
				sb.append(" != null");
				flag = true;
			}
		}
		XmlElement ifElement = new XmlElement("if");
		ifElement.addAttribute(new Attribute("test", sb.toString()));
		return ifElement;
	}
}


相關推薦

maven+mybatis+mybatis-generator+sql server 2005自動生成程式碼加上定義外掛批量插入更新外掛

第一步:準備需要的jar包。由於maven只要配置pom.xml就可以從倉庫下載jar包。因此我們首先配置pom.xml。 注意com.microsoft.sqlserver需要自己加入maven倉庫的。 <dependencies> ......

SpringBoot入門篇--整合mybatis+generator自動生成程式碼+druid連線池+PageHelper外掛

我們這一一篇部落格講的是如何整合Springboot和Mybatis框架,然後使用generator自動生成mapper,pojo等檔案。然後再使用阿里巴巴提供的開源連線池druid,這個連線池的好處我就不說了,集合了所有連線池的好處,並且還提供了監控等功能,加大了可擴充套件性等等。   1.&

MavenMybatis逆向工程的使用(自動生成程式碼

1、新增maven外掛,讓maven環境支援mybatis-generator元件在pom.xml裡面新增如下程式碼: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XML

Mybatis Generator(MBG)自動生成daoentity mapper.xml對映

1.在pom.xml中引入依賴 <!--mybatis-generator 自動生成工具--> <dependency> <groupId>org.mybatis.generator

SpringCloud+MyBatis(oracle)逆向工程自動生成程式碼

一、何為逆向工程?     平時我們的開發過程,除了系統框架的搭建。其他無非就是CRUD增刪改查的程式碼邏輯搬磚,CRUD也就避免不了要跟資料庫打交道。一般常見的資料庫操作insert(增)、update(改)、select(查)、delete(刪);常規傳統的資料庫層面

mybatis反向工程generatorSqlmap-increase自動生成程式碼還有一點引數校驗

之前都是大佬搭框架我寫業務程式碼,知道mybatis能自動生成程式碼,但是從來沒自己操作過,菜雞。 一開始我是用springboot的mybatis外掛生成的,但是生成的程式碼裡方法很少,沒有各個欄位的操作,所以又用generatorSqlmap-increase做了一次,

spring+springmvc+mybatis(3)--逆向工程自動生成程式碼

1.what? mybatis需要程式設計師自己寫sql語句,mybatis官方提供逆向工程,可以針對表單自動生成mybatis執行所需要的程式碼(mapper.java,mapper.xml,poj

關於SQL Server 2005服務無法啟動報3417錯誤。(附帶重灌SQL時解決COM+目錄問題)(轉帖)

那天很是鬱悶,由於長期沒有使用SQL Server 2005,那天用時候居然伺服器啟動不到,報3417錯誤。。。當時沒有找到解決方案,不得已,只有重灌了。那個痛苦哦。。。解除安裝就要花費二三十分鐘,安裝又要用掉一個小時。。。(這是SQL 2005,後來裝SQL 2008的時候

使用mybatis-generator新增定義外掛時提示無法例項化外掛

import org.mybatis.generator.api.CommentGenerator; import org.mybatis.generator.api.IntrospectedTable; import org.mybatis.generator.api.PluginAdapter; impo

python連結資料庫SQL Server 2005出錯怎麼辦???附解決方案以及開啟TCP/IP協議檢視預設埠的過程

import pymssql conn=pymssql.connect(host='127.0.0.1:1433',user='sa',password='jxn',database='scott',charset="UTF-8") ''' 如果和本機資料庫互動,只需修改連結

SQL Server——保證資料的完整性(使用者定義資料型別、使用規則、解除刪除規則)

目錄   一、使用者自定義資料型別 二、使用規則 規則和CHECK約束的比較: 三、解除和刪除規則 一、使用者自定義資料型別 使用者自己設計並實現的資料型別就是使用者自定義資料型別。舉例:當幾個表中要存同種資料型別時,並且保證他們有相同的資料型別、長度和

Mybatis定義外掛後報錯處理

前端時間,模仿pageHelper作者的Mybatis分頁外掛,自己修改並優化了一下,放在專案裡執行後,卻報錯,報錯如下 Exception in thread "main" org.apache.ibatis.exceptions.PersistenceException

MyBatis攔截器定義外掛實現

MyBaits是一個開源的優秀的持久層框架,SQL語句與程式碼分離,面向配置的程式設計,良好支援複雜資料對映,動態SQL;MyBatis 是支援定製化 SQL、儲存過程以及高階對映的優秀的持久層框架。MyBatis 避免了幾乎所有的 JDBC 程式碼和手動設定引數以及獲取結果集。MyBatis 可以對配置和原

Spring boot入門(三):SpringBoot整合結合AdminLTE(Freemarker)利用generate自動生成程式碼利用DataTablePageHelper進行顯示

  關於SpringBoot和PageHelper,前篇部落格已經介紹過Spring boot入門(二):Spring boot整合MySql,Mybatis和PageHelper外掛,前篇部落格大致講述了SpringBoot如何整合Mybatis和Pagehelper,但是沒有做出實際的範例,本篇部落格是連

mybatis-generator-maven-plugin外掛自動生成程式碼的配置方法

1. 第一步,在pom檔案中引入如下外掛   //專案示例程式碼: <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-g

使用Intellij IDEA在maven專案中整合mybatis-generator外掛自動生成程式碼

1.在dependencies下新增: <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artif

idea+springboot2.0+maven+mybatis+mybatis generator自動生成程式碼

    最近嘗試自己搭一主流的springboot框架,springboot全家桶相對於springmvc來說,少了很多的配置,並且內建tomcat,打包即可釋出,適合輕量級系統開發,一下是配置的具體的過程。 1、jdk1.8 2、填寫GroupId和Artifact

maven專案自動生成程式碼mybatis-generator 程式碼自動生成

1.本地安裝maven,配置好環境變數 2.在專案下的jdbc檔案中引用相關mapper外掛:(拷貝以下程式碼,修改相關路徑) jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/test?

maven使用mybatis-generator自動生成程式碼

1. 在pom.xml檔案中新增mybatis-generator外掛 在project節點下新增如下程式碼: <build> <finalName></finalName> <plugins> <plu

IntelliJ IDEA Maven Mybatis generator 自動生成程式碼 MAC系統

版本 系統:MAC系統 java:8.x maven:3.x Mybatis:3.4.5 風.fox JDK 設定 Maven 設定 新建 IDEA Maven 專案 開啟IDEA,點選Create New Projec