mybatisModelToSql,通过实体获得sql

package xxx;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import org.apache.commons.lang3.StringUtils;

/**

  • @author dd

  • @version 1.0

  • @date 2022/1/4 11:24
    */
    public class MybatisModelToSql {

    public static void getProxyPojoValue(Object object, Set< String > key1){
    String id = null;
    // 返回参数
    HashMap<String, Object> hashMap = new HashMap<>(16);
    for (String s : key1) {
    Field[] fields = object.getClass().getDeclaredFields();
    for (Field field : fields) {
    field.setAccessible(true);
    // 获取表名
    TableName table = object.getClass().getAnnotation(TableName.class);
    if (table != null) {
    String tableName = table.value();
    hashMap.putIfAbsent(“tableName”, tableName);
    }
    // 获取主键id
    if (id == null) {
    boolean isIdField = field.isAnnotationPresent(TableId.class);
    if (isIdField) {
    TableField tableField = field.getAnnotation(TableField.class);
    if (s.toLowerCase().equals(field.getName().toLowerCase())) {
    String tableId = tableField.value();
    hashMap.put(s, tableId);
    id = tableId;
    }
    }
    }
    // 获取字段的值
    boolean isTableField = field.isAnnotationPresent(TableField.class);
    if (isTableField) {
    TableField tableField = field.getAnnotation(TableField.class);
    if (s.toLowerCase().equals(field.getName().toLowerCase())) {
    String fieldValue = tableField.value();
    hashMap.put(s, fieldValue);
    }
    }
    }
    }
    System.out.println(hashMap);
    }

    public static String getInsertSql(Object object){
    String result = “”;
    StringBuilder sql = new StringBuilder();
    sql.append(“insert into “);
    Field[] fields = object.getClass().getDeclaredFields();
    // 获取表名
    TableName table = object.getClass().getAnnotation(TableName.class);
    if (table != null) {
    String tableName = table.value();
    sql.append(tableName + " (”);
    }
    for (int i = 0;i<fields.length;i++) {
    boolean isTableField = fields[i].isAnnotationPresent(TableField.class);
    if(isTableField){
    TableField tableField = fields[i].getAnnotation(TableField.class);
    sql.append(tableField.value()).append(”,");
    }
    }
    String substring = sql.substring(0, sql.toString().length() - 1);
    sql = new StringBuilder(substring);
    sql.append(" ) values ( ");
    result = sql.toString();
    return result;
    }

    /**

    • 获取插入语句
    • @param entity
    • @return
      */
      public String createInsert(T entity) {
      String sql = "Insert into ";
      String column = “”; // 列
      String c_values = “”; // 列值
      List<Map<String, Object>> list = getFiledListInfo(entity);
      sql += list.get(0).get(“obj_name”).toString() + " ";
      for (int i = 0; i < list.size(); i++) {
      //約定id在數據庫自動生成-20130807
      if (null != list.get(i).get(“f_name”) && list.get(i).get(“f_name”).toString() == “id”){
      i++;
      }
      if (list.get(i).get(“f_value”) != null) {
      // System.out.println(“属性数据类型:” + list.get(i).get(“f_type”));
      column += list.get(i).get(“f_name”) + “,”;
      if(list.get(i).get(“f_type”).toString().contains(“Date”)){
      c_values += list.get(i).get(“f_value”) + “,”;
      }else {
      c_values += “’” + list.get(i).get(“f_value”) + “’,”;
      }
      }
      }
      sql += “(” + column.substring(0, column.length() - 1) + “) values (”
      + c_values.substring(0, c_values.length() - 1) + “);”;
      return sql;
      }

    /**

    • 获取插入语句 适合主键编辑
    • @param entity
    • @return
      */
      public String createUpdate(T entity) {
      String sql = "update ";
      String column = “”; // 列
      String c_values = “”; // 列值
      List<Map<String, Object>> list = getFiledListInfo(entity);
      sql += list.get(0).get(“obj_name”).toString() + " set ";
      for (int i = 0; i < list.size(); i++) {
      //約定id在數據庫自動生成-20130807
      if (null != list.get(i).get(“f_name”) && list.get(i).get(“f_name”).toString() == “id”){
      i++;
      }
      if (list.get(i).get(“f_value”) != null) {
      // System.out.println(“属性数据类型:” + list.get(i).get(“f_type”));
      // column += list.get(i).get(“f_name”) + “=”;
      if(list.get(i).get(“f_type”).toString().contains(“Date”)){
      c_values = list.get(i).get(“f_value”) + “,”;
      }else {
      c_values = “’” + list.get(i).get(“f_value”) + “’,”;
      }
      column += list.get(i).get(“f_name”) + “=” + c_values;
      }
      }
      sql += column.substring(0, column.length() - 1) + " where " +list.get(0).get(“f_name”)+ “=” + “’” + list.get(0).get(“f_value”) + “’”;
      return sql;
      }

    /**

    • 根据属性名获取属性值
    • */
      protected Object getFieldValueByName(String fieldName, Object o) {
      try {
      String firstLetter = fieldName.substring(0, 1).toUpperCase();
      String getter = “get” + firstLetter + fieldName.substring(1);
      Method method = o.getClass().getMethod(getter, new Class[] {});
      Object value = method.invoke(o, new Object[] {});
      return value;
      } catch (Exception e) {
      // log.error(e.getMessage(), e);
      return null;
      }
      }

    /**

    • 类名(obj_name)获取属性类型(f_type),属性名(f_name),属性值(f_value)的map组成的list

    • @param o Object

    • @return List
      */
      protected List getFiledListInfo(Object o) {

      String obj_name = o.getClass().getSimpleName().toString();
      // 获取表名
      TableName table = o.getClass().getAnnotation(TableName.class);
      String tableName = “”;
      if (table != null) {
      tableName = table.value();
      }
      Field[] fields = o.getClass().getDeclaredFields();
      String[] fieldNames = new String[fields.length];
      List list = new ArrayList();
      Map<String, Object> infoMap;

      for (int i = 0; i < fields.length; i++) {
      infoMap = new HashMap<String, Object>();

// infoMap.put(“obj_name”, obj_name);
infoMap.put(“obj_name”, tableName);
infoMap.put(“f_type”, fields[i].getType().getName());
boolean isTableField = fields[i].isAnnotationPresent(TableField.class);
if(isTableField){
TableField tableField = fields[i].getAnnotation(TableField.class);
infoMap.put(“f_name”, tableField.value());
}
// infoMap.put(“f_name”, fields[i].getName());
boolean validDate = false;
if(null != getFieldValueByName(fields[i].getName(), o)){
validDate = isDate(getFieldValueByName(fields[i].getName(), o).toString(),DateUtils.YYYY_MM_DD_HH_MM_SS);
}
if(validDate){
infoMap.put(“f_value”, getFieldValueByName(fields[i].getName(), o));
}else {
boolean check = checkType(infoMap.get(“f_type”).toString());
if(check){
if(null != getFieldValueByName(fields[i].getName(), o)){
infoMap.put(“f_value”, “STR_TO_DATE(’”+getFieldValueByName(fields[i].getName(), o)+"’,’%W %M %d %H:%i:%S CST %Y’)");
}else {
infoMap.put(“f_value”,null);
}
}else {
infoMap.put(“f_value”, getFieldValueByName(fields[i].getName(), o));
}
}
list.add(infoMap);
}
return list;
}

/**
 * 判断字符串是否为日期
 * @param value
 * @param format
 * @return
 */
public static boolean isDate(String value,String format){

    SimpleDateFormat sdf = null;
    ParsePosition pos = new ParsePosition(0);//指定从所传字符串的首位开始解析

    if(StringUtils.isBlank(value)|| StringUtils.isBlank(format)){
        return false;
    }
    try {
        sdf = new SimpleDateFormat(format);
        sdf.setLenient(false);
        Date date = sdf.parse(value,pos);
        if(date == null){
            return false;
        }else{
            //更为严谨的日期,如2011-03-024认为是不合法的
            if(pos.getIndex() > sdf.format(date).length()){
                return false;
            }
            return true;
        }
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

 // 判断属性类型
 protected boolean checkType(String f_type) {
 if (f_type.contains("Date")) {
     return true;
 }
 return false;
 }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值