`

通过javaBean反射转换成mybatis映射文件

阅读更多
package mysql.tool;

import java.util.List;

import mysql.model.LoanTransferDto;

public class MapperUtils {
	
	public static String genBaseResultMap(Class<?> clazz){
		 List<String> fieldList = BeanUtil.getBeanPropertyList(clazz);
		 StringBuffer sb = new StringBuffer();
		 sb.append("<resultMap id=\"BaseResultMap\" type=\""+clazz.getSimpleName().toUpperCase()+"\">\r\n");
		 int index = 0;
		 for (String fields : fieldList) {
			  String[] fieldArr = fields.split("`");
			  String columnStr = toColumn(fieldArr[1]);
			  if(index==0){
				  sb.append("  <id column=\""+columnStr+"\" jdbcType=\"BIGINT\" property=\""+fieldArr[1]+"\" />\r\n");
			  }else{
				  String jdbcType = "varchar";
				  if(fieldArr[0].equals("int")||fieldArr[0].equals("Integer")){
					  jdbcType = "Integer";
				  }else if(fieldArr[0].equals("long")||fieldArr[0].equals("Long")){
					  jdbcType = "bigInt";
				  }else if(fieldArr[0].equals("Date")||fieldArr[1].contains("Time")||fieldArr[1].contains("Date")){
					  jdbcType = "TIMESTAMP";
				  }
				  sb.append("  <result column=\""+columnStr+"\" jdbcType=\""+jdbcType.toUpperCase()+"\" property=\""+fieldArr[1]+"\" />\r\n");
			  }
			  index++;
		 }
		 sb.append("</resultMap>\r\n");
		 return sb.toString();
	}
	
	//生成删除语句
	public static String genDeleteMap(String tableNamePreFix,Class<?> clazz){
		 List<String> fieldList = BeanUtil.getBeanPropertyList(clazz);
		 String tableName =(tableNamePreFix+toColumn(clazz.getSimpleName())).toUpperCase();
		 StringBuffer sb = new StringBuffer();
		 sb.append("<delete id=\"deleteByPrimaryKey\" parameterType=\"java.lang.Long\">\r\n");
		 sb.append("   delete from "+tableName+"  where id = #{id,jdbcType=BIGINT}\r\n");
		 sb.append("</delete>\r\n");
		 return sb.toString();
	}
	
	//生成插入语句
	public static String genInsertMap(String tableNamePreFix,Class<?> clazz){
		 List<String> fieldList = BeanUtil.getBeanPropertyList(clazz);
		 String tableName =(tableNamePreFix+toColumn(clazz.getSimpleName())).toUpperCase();
		 StringBuffer sb = new StringBuffer();
		 sb.append("<insert id=\"insert\" parameterType=\""+clazz.getSimpleName().toUpperCase()+"\">\r\n");
		 StringBuffer columnAppend = new StringBuffer();
		 StringBuffer valuesAppend = new StringBuffer();
		 int index = 0;
		 String idFields = "";
		 for (String fields : fieldList) {
			  String[] fieldArr = fields.split("`");
			  if(index>0){
				  String jdbcType = "varchar";
				  if(fieldArr[0].equals("int")||fieldArr[0].equals("Integer")){
					  jdbcType = "Integer";
				  }else if(fieldArr[0].equals("long")||fieldArr[0].equals("Long")){
					  jdbcType = "bigInt";
				  }else if(fieldArr[0].equals("Date")||fieldArr[1].contains("Time")||fieldArr[1].contains("Date")){
					  jdbcType = "TIMESTAMP";
				  }
				  columnAppend.append("    "+toColumn(fieldArr[1])+",\r\n");
				  valuesAppend.append("    #{"+fieldArr[1]+",jdbcType="+jdbcType.toUpperCase()+"},\r\n");
			  }else{
				  idFields = fieldArr[1];
			  }
			  index++;
		 }
		 columnAppend.deleteCharAt(columnAppend.lastIndexOf(","));
		 valuesAppend.deleteCharAt(valuesAppend.lastIndexOf(","));
		 sb.append("  insert into "+tableName+"("+columnAppend.toString()+") values("+valuesAppend+")\r\n");
		 sb.append("</insert>\r\n");
		 return sb.toString();
	}
	
	//生成更新语句
	public static String genUpdateMap(String tableNamePreFix,Class<?> clazz){
		 List<String> fieldList = BeanUtil.getBeanPropertyList(clazz);
		 String tableName =(tableNamePreFix+toColumn(clazz.getSimpleName())).toUpperCase();
		 StringBuffer sb = new StringBuffer();
		 sb.append("<update id=\"updateByPrimaryKey\" parameterType=\""+clazz.getSimpleName().toUpperCase()+"\">\r\n");
		 StringBuffer setAppend = new StringBuffer();
		 sb.append("  update "+tableName+" set\r\n");
		 int index = 0;
		 String idFields = "";
		 for (String fields : fieldList) {
			  String[] fieldArr = fields.split("`");
			  if(index>0){
				  String jdbcType = "varchar";
				  if(fieldArr[0].equals("int")||fieldArr[0].equals("Integer")){
					  jdbcType = "Integer";
				  }else if(fieldArr[0].equals("long")||fieldArr[0].equals("Long")){
					  jdbcType = "bigInt";
				  }else if(fieldArr[0].equals("Date")||fieldArr[1].contains("Time")||fieldArr[1].contains("Date")){
					  jdbcType = "TIMESTAMP";
				  }
				  String column = toColumn(fieldArr[1]);
				  setAppend.append("    "+column+" = #{"+fieldArr[1]+",jdbcType="+jdbcType.toUpperCase()+"},\r\n");
			  }else{
				  idFields = fieldArr[1];
			  }
		      index++;
		 }
		 setAppend.deleteCharAt(setAppend.lastIndexOf(","));
		 sb.append(setAppend.toString());
		 sb.append("  where "+toColumn(idFields)+" = #{"+idFields+",jdbcType=BIGINT}\r\n");
		 sb.append("</update>\r\n");
		 return sb.toString();
	}
	
	//生成更新语句
	public static String genSelectByIdMap(String tableNamePreFix,Class<?> clazz){
		 List<String> fieldList = BeanUtil.getBeanPropertyList(clazz);
		 String tableName =(tableNamePreFix+toColumn(clazz.getSimpleName())).toUpperCase();
		 StringBuffer sb = new StringBuffer();
		 sb.append("<select id=\"selectByPrimaryKey\" parameterType=\"java.lang.Long\" resultMap=\"BaseResultMap\">\r\n");
		 StringBuffer columnAppend = new StringBuffer();
		 StringBuffer valuesAppend = new StringBuffer();
		 int index = 0;
		 String idFields = "";
		 for (String fields : fieldList) {
			  String[] fieldArr = fields.split("`");
			  if(index>0){
				  String jdbcType = "varchar";
				  if(fieldArr[0].equals("int")||fieldArr[0].equals("Integer")){
					  jdbcType = "Integer";
				  }else if(fieldArr[0].equals("long")||fieldArr[0].equals("Long")){
					  jdbcType = "bigInt";
				  }else if(fieldArr[0].equals("Date")||fieldArr[1].contains("Time")||fieldArr[1].contains("Date")){
					  jdbcType = "TIMESTAMP";
				  }
				  columnAppend.append("    "+toColumn(fieldArr[1])+",\r\n");
				  valuesAppend.append("    #{"+fieldArr[1]+",jdbcType="+jdbcType.toUpperCase()+"},\r\n");
			  }else{
				  idFields = fieldArr[1];
			  }
			  index++;
		 }
		 columnAppend.deleteCharAt(columnAppend.lastIndexOf(","));
		 valuesAppend.deleteCharAt(valuesAppend.lastIndexOf(","));
		 sb.append("  select "+columnAppend.toString()+" from "+tableName+" ");
		 sb.append("  where "+toColumn(idFields)+" = #{"+idFields+",jdbcType=BIGINT}\r\n");
		 sb.append("</select>\r\n");
		 return sb.toString();
	}
		
	
	public static String toColumn(String word) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < word.length(); i++) {
			char c = word.charAt(i);
			if (Character.isUpperCase(c)) {
				sb.append("_"+c);
			}else{
				sb.append(c);
			}
		}
		return sb.toString().toLowerCase();
	}
	
	public static void main(String[] args) {
		System.out.println(genBaseResultMap(LoanTransferDto.class));
		System.out.println(genDeleteMap("JGJ",LoanTransferDto.class));
		System.out.println(genInsertMap("JGJ",LoanTransferDto.class));
		System.out.println(genUpdateMap("JGJ",LoanTransferDto.class));
		System.out.println(genSelectByIdMap("JGJ",LoanTransferDto.class));
		//System.out.println(toColumn("loanType"));
	}

}

 

 

生成后的效果:

 

<resultMap id="BaseResultMap" type="LOANTRANSFERDTO">
  <id column="ltid" jdbcType="BIGINT" property="ltid" />
  <result column="mid" jdbcType="BIGINT" property="mid" />
  <result column="loan_no" jdbcType="VARCHAR" property="loanNo" />
  <result column="title" jdbcType="VARCHAR" property="title" />
  <result column="bid_count" jdbcType="BIGINT" property="bidCount" />
  <result column="bid_amount" jdbcType="BIGINT" property="bidAmount" />
  <result column="rate" jdbcType="BIGINT" property="rate" />
  <result column="transfer_amount" jdbcType="BIGINT" property="transferAmount" />
  <result column="loan_cycle" jdbcType="BIGINT" property="loanCycle" />
  <result column="loan_cycle_attr" jdbcType="INTEGER" property="loanCycleAttr" />
  <result column="update_time" jdbcType="TIMESTAMP" property="updateTime" />
  <result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
</resultMap>

 

<delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
   delete from JGJ_LOAN_TRANSFER_DTO  where id = #{id,jdbcType=BIGINT}
</delete>

 

<insert id="insert" parameterType="LOANTRANSFERDTO">
  insert into JGJ_LOAN_TRANSFER_DTO(    mid,
    loan_no,
    title,
    bid_count,
    bid_amount,
    rate,
    transfer_amount,
    loan_cycle,
    loan_cycle_attr,
    update_time,
    create_time
) values(    #{mid,jdbcType=BIGINT},
    #{loanNo,jdbcType=VARCHAR},
    #{title,jdbcType=VARCHAR},
    #{bidCount,jdbcType=BIGINT},
    #{bidAmount,jdbcType=BIGINT},
    #{rate,jdbcType=BIGINT},
    #{transferAmount,jdbcType=BIGINT},
    #{loanCycle,jdbcType=BIGINT},
    #{loanCycleAttr,jdbcType=INTEGER},
    #{updateTime,jdbcType=TIMESTAMP},
    #{createTime,jdbcType=TIMESTAMP}
)
</insert>

 

<update id="updateByPrimaryKey" parameterType="LOANTRANSFERDTO">
  update JGJ_LOAN_TRANSFER_DTO set
    mid = #{mid,jdbcType=BIGINT},
    loan_no = #{loanNo,jdbcType=VARCHAR},
    title = #{title,jdbcType=VARCHAR},
    bid_count = #{bidCount,jdbcType=BIGINT},
    bid_amount = #{bidAmount,jdbcType=BIGINT},
    rate = #{rate,jdbcType=BIGINT},
    transfer_amount = #{transferAmount,jdbcType=BIGINT},
    loan_cycle = #{loanCycle,jdbcType=BIGINT},
    loan_cycle_attr = #{loanCycleAttr,jdbcType=INTEGER},
    update_time = #{updateTime,jdbcType=TIMESTAMP},
    create_time = #{createTime,jdbcType=TIMESTAMP}
  where ltid = #{ltid,jdbcType=BIGINT}
</update>

 

<select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
  select     mid,
    loan_no,
    title,
    bid_count,
    bid_amount,
    rate,
    transfer_amount,
    loan_cycle,
    loan_cycle_attr,
    update_time,
    create_time
 from JGJ_LOAN_TRANSFER_DTO   where ltid = #{ltid,jdbcType=BIGINT}
</select>

 

分享到:
评论

相关推荐

    mybatis源码

    MyBatis可以使用简单的XML或注解进行配置和原始映射,将接口和Java的POJOs(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录。 在深入MyBatis源码之前,我们需要了解一些基础概念。MyBatis的核心组件...

    mybatis源码分析

    1. SQL映射文件与XML配置:MyBatis的核心在于SQL映射文件,它们定义了SQL语句、参数和结果映射。XML配置文件用于设置数据源、事务管理器等基础信息,同时也可以通过注解方式进行配置,使得代码更加简洁。 2. ...

    看黑马Mybatis, Spring, SpringMVC自己记得笔记.docx

    当我们在 MyBatis 的映射文件中配置了 resultType 之后,MyBatis 会根据这个配置项来将数据库查询结果转换为指定的 Java 对象。 2. MyBatis 中的 resultmap 和 resulttype 的区别:resultmap 是 MyBatis 中的一种...

    mybatis:mybatis原始中文注释

    MyBatis支持自动映射和手动映射,可以精确控制字段到Java对象的转换。 9. **缓存机制**: MyBatis内置了两级缓存,一级缓存是SqlSession级别的,二级缓存是Mapper级别的。通过缓存,可以提高数据访问的效率。 10. *...

    MyBatisInsider:MyBatis原始码阅读笔记

    DefaultResultSetHandler是默认实现,通过反射和TypeHandler来处理结果。 9. **TypeHandler** TypeHandler是MyBatis的类型处理器,用于Java类型与JDBC类型之间的转换。MyBatis内置了很多常见类型的TypeHandler,...

    映射ResultSet结果

    这种技术通常结合了反射和类型转换,使得我们可以快速地将数据库查询结果转换为业务对象。 下面是一个简单的例子,展示了如何实现一个`ResultSetMapper`类来自动映射`ResultSet`到JavaBean: ```java public class...

    Oracle - Javabean Generator-开源

    这些框架通过反射机制调用JavaBean的getter和setter方法,自动完成数据的读写,极大地提高了开发效率。 除此之外,Oracle Bean Generator还可能包含其他附加功能,如生成DAO接口和实现类,或者创建JUnit测试用例。...

    fastjson-jar-源代码

    4. **自动转换**:Fastjson可以自动将JavaBean属性映射到JSON字段,反之亦然,极大地简化了数据处理。 5. **流式解析和生成**:Fastjson提供了流式处理模式,适合处理大数据量的情况,避免一次性加载整个JSON内容到...

    Spring.3.x企业应用开发实战(完整版).part2

    1.5.4 通用类型转换系统和属性格式化系统 1.5.5 数据访问层新增OXM功能 1.5.6 Web层的增强 1.5.7 其他 1.6 Spring对Java版本的要求 1.7 如何获取Spring 1.8 小结 第2章 快速入门 2.1 实例功能概述 2.1.1 比Hello ...

    Spring3.x企业应用开发实战(完整版) part1

    1.5.4 通用类型转换系统和属性格式化系统 1.5.5 数据访问层新增OXM功能 1.5.6 Web层的增强 1.5.7 其他 1.6 Spring对Java版本的要求 1.7 如何获取Spring 1.8 小结 第2章 快速入门 2.1 实例功能概述 2.1.1 比Hello ...

    三大框架SSH)面试题

    2. **读取并解析映射信息,创建SessionFactory:** 接着,Hibernate会读取实体类与数据库表之间的映射信息(通常存储在`.hbm.xml`文件或通过注解定义)。基于这些信息,Hibernate构建一个`SessionFactory`实例,它是...

    JavaWeb

    它们封装了业务逻辑,可以被JSP页面或者Servlet通过Java反射机制实例化和操作。JavaBean通过属性、构造器和方法提供数据访问和处理,增强了代码的复用性。 四、MVC模式 Model-View-Controller(MVC)是JavaWeb开发...

Global site tag (gtag.js) - Google Analytics