package com.hx.mybatis.aes.springbean; import com.gitee.sunchenbin.mybatis.actable.annotation.Column; import com.gitee.sunchenbin.mybatis.actable.annotation.Table; import com.hx.common.annotations.MysqlHexAes; import com.hx.common.dao.CommonMapper; import com.hx.common.service.CommonService; import com.hx.exception.ServiceException; import com.hx.mybatisTool.SqlSentence; import com.hx.util.StringUtils; import com.hx.util.mysql.aes.MysqlHexAesTool; import javax.annotation.PostConstruct; import java.lang.reflect.Field; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; public class InitMysqlData { /** * 项目启动就执行后就执行该方法 */ @PostConstruct public static void initData(String packPath, CommonService commonService){ //项目启动的时候填入 if(!StringUtils.isEmpty(packPath)){ Set> classes = VariableAesKey.classData(packPath); Map aesKeysFild = new HashMap<>(); boolean isAes = false; String tableName = null; String fildName = null; String fildValue = null; SqlSentence sqlSentence = new SqlSentence(); Map values = new HashMap<>(); for(Class cl:classes){ //表名称 boolean hasAnnotation = cl.isAnnotationPresent(Table.class); if(!hasAnnotation){ continue; } Table table = cl.getAnnotation(Table.class); tableName = table.name(); aesKeysFild = new HashMap<>(); isAes = false; // 取得本类的全部属性 Field[] fields = cl.getDeclaredFields(); fields = VariableAesKey.getPatentFields(fields,cl); for (Field field:fields) { fildName = null; // 判断方法中是否有指定注解类型的注解 hasAnnotation = field.isAnnotationPresent(MysqlHexAes.class); if (hasAnnotation) { // 根据注解类型返回方法的指定类型注解 MysqlHexAes mysqlHexAes = field.getAnnotation(MysqlHexAes.class); //String aesKeyField = mysqlHexAes.aesKeyField(); String aesKey = mysqlHexAes.aesKey(); if(StringUtils.isEmpty(aesKey)){ aesKey = VariableAesKey.AES_KEY; if(StringUtils.isEmpty(aesKey)){ throw new RuntimeException("mysql的AES秘钥不能为空:"+field.getName()); } } hasAnnotation = field.isAnnotationPresent(Column.class); if(hasAnnotation){ Column column = field.getAnnotation(Column.class); fildName = column.name(); } if(StringUtils.isEmpty(fildName)){ fildName = field.getName(); } sqlSentence.sqlSentence("SELECT id,"+fildName+" FROM "+tableName,values); List> list = commonService.selectListMap(CommonMapper.class,sqlSentence); for(Map map:list){ fildValue = (String)map.get(fildName); System.out.println("fildValue:"+fildValue); if(StringUtils.isEmpty(fildValue)){ continue; } if(fildValue.length()%32==0 && MysqlHexAesTool.isHexStrValid(fildValue)){ continue; } values.clear(); values.put("id",map.get("id")); values.put("filedData",fildValue); sqlSentence.sqlSentence("UPDATE "+tableName+" SET "+fildName+" = #{m.filedData} WHERE id = #{m.id}",values); if(commonService.updateSentence(sqlSentence)!=1){ throw new ServiceException("更新超过1条,更新失败!"); } } } } } } } }