import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @Description : sql工具类
* @Author : cxw
* @Date : 2023/8/3 14:31
* @Version : 1.0
**/
public class SQLUtil {
private static Logger logger = LoggerFactory.getLogger(SQLUtil.class);
private static Pattern humpPattern = Pattern.compile("[A-Z]");
/**
* 创建插入sql
* @param tableName 数据库表名
* @param obj 类对象
* @return
*/
public static String createInsertSQL(String tableName, Object obj)throws Exception{
StringBuilder sql=new StringBuilder();
sql.append(" INSERT INTO ").append(tableName).append(" ");
String field="";
String values="";
List<Field> fieldList = getAllFields(obj.getClass());
for(Field f : fieldList){
f.setAccessible(true);
// 获取字段上的注解对象
Annotation[] annotations = f.getDeclaredAnnotations();
String tableField = hasBuilderField(annotations);
if(tableField==null)tableField=humpToLine(f.getName());
field += tableField+",";
values += ":"+f.getName()+",";
}
field = field.substring(0, field.length() - 1);
values = values.substring(0, values.length() - 1);
sql.append("(").append(field).append(")").append(" VALUES ");
sql.append("(").append(values).append(")").append(" ");
logger.debug("【insert sql】={}",sql.toString());
return sql.toString();
}
/**
* 创建更新sql 类对象字段值为null的也更新
* @param tableName 表名
* @param idField 主键id
* @param obj 类对象
* @return
*/
public static String createUpdateNullSQL(String tableName,String idField, Object obj){
StringBuilder sql=new StringBuilder();
sql.append(" UPDATE ").append(tableName).append(" SET ");
String where=" where "+idField+"=:"+idField;
List<Field> fieldList = getAllFields(obj.getClass());
for(Field f : fieldList){
f.setAccessible(true);
// 获取字段上的注解对象
Annotation[] annotations = f.getDeclaredAnnotations();
String tableField = hasBuilderField(annotations);
if(tableField==null)tableField=humpToLine(f.getName());
if(tableField.equals(idField))continue;
sql.append(tableField).append(" = ").append(":").append(f.getName()).append(",");
}
String result = sql.toString().toString();
result = result.substring(0, result.length() - 1);
result = result+where;
logger.debug("【update sql】={}",result);
return result;
}
/**
* 创建更新sql 类对象字段值为null不更新
* @param tableName 表名
* @param idField 主键id
* @param obj 类对象
* @return
*/
public static String createUpdateNotNullSQL(String tableName,String idField, Object obj) throws Exception {
StringBuilder sql=new StringBuilder();
sql.append(" UPDATE ").append(tableName).append(" SET ");
String where=" where "+idField+"=:"+idField;
List<Field> fieldList = getAllFields(obj.getClass());
for(Field f : fieldList){
f.setAccessible(true);
if(f.get(obj)==null)continue;
// 获取字段上的注解对象
Annotation[] annotations = f.getDeclaredAnnotations();
String tableField = hasBuilderField(annotations);
if(tableField==null)tableField=humpToLine(f.getName());
if(tableField.equals(idField))continue;
sql.append(tableField).append(" = ").append(":").append(f.getName()).append(",");
}
String result = sql.toString().toString();
result = result.substring(0, result.length() - 1);
result = result+where;
logger.debug("【update sql】={}",result);
return result;
}
/**
* 创建查询sql
* @param tableName 表名
* @param obj 类对象
* @return
*/
public static String createQuerySQL(String tableName,Object obj) throws Exception {
StringBuilder sql=new StringBuilder();
sql.append(" select * from ").append(tableName).append(" where ");
List<Field> fieldList = getAllFields(obj.getClass());
for(Field f : fieldList){
f.setAccessible(true);
if(f.get(obj)==null)continue;
// 获取字段上的注解对象
Annotation[] annotations = f.getDeclaredAnnotations();
String tableField = hasBuilderField(annotations);
if(tableField==null)tableField=humpToLine(f.getName());
sql.append(tableField).append(" = ").append(":").append(f.getName()).append(" and ");
}
String result = sql.toString().toString();
result = result.substring(0, result.length() - 4);
logger.debug("【query sql】={}",result);
return result;
}
/**
* 创建变量
* @param obj
* @param hasNull 是否包含null的值
* @return
*/
public static MapSqlParameterSource createParam(Object obj,Boolean hasNull){
MapSqlParameterSource mapSqlParameterSource = new MapSqlParameterSource();
try{
List<Field> fieldList = getAllFields(obj.getClass());
for(Field f : fieldList){
f.setAccessible(true);
if(!hasNull&&f.get(obj)==null)continue;
mapSqlParameterSource.addValue(f.getName(), f.get(obj));
}
return mapSqlParameterSource;
}catch(Exception e){
}
return null;
}
private static List<Field> getAllFields(Class<?> cls){
List<Field> fieldList = new ArrayList<Field>();
while(null != cls){
fieldList.addAll(Arrays.asList(cls.getDeclaredFields()));
//得到父类,然后赋给自己
cls = cls.getSuperclass();
}
return fieldList;
}
/**
* 驼峰转下划线
* @param str
* @return
*/
public static String humpToLine(String str){
Matcher matcher = humpPattern.matcher(str);
StringBuffer sb = new StringBuffer();
while(matcher.find()){
matcher.appendReplacement(sb, "_"+matcher.group(0).toLowerCase());
}
matcher.appendTail(sb);
return sb.toString();
}
/**
* 判断是否存在BuilderField注解
* @param annotations
* @return
*/
public static String hasBuilderField(Annotation[] annotations) {
if(annotations==null||annotations.length==0)return null;
for (Annotation annotation : annotations) {
if(annotation instanceof BuilderField){
return ((BuilderField) annotation).name();
}
}
return null;
}
}