@Service
public class TestServiceImpl {
@Autowired
org.apache.ibatis.session.SqlSessionFactory sessionFactory;
/**
*@author lixiao
*@date 2023/4/27 10:38
*@Description: 修改单个
*/
public void test1(){
try {
Configuration configuration = sessionFactory.getConfiguration();
//Mapper的全路径加方法名
String id = "com.xxx.xx.XxxMapper.test";
MappedStatement mappedStatement = configuration.getMappedStatement(id, false);
RawSqlSource sqlSource = (RawSqlSource)mappedStatement.getSqlSource();
Field sqlSource1 = sqlSource.getClass().getDeclaredField("sqlSource");
sqlSource1.setAccessible(true);
Object o = sqlSource1.get(sqlSource);
Field sql1 = o.getClass().getDeclaredField("sql");
sql1.setAccessible(true);
BoundSql boundSql = sqlSource.getBoundSql(mappedStatement);
String sql = boundSql.getSql();
String newSql = sql.replace("cn", "en");
sql1.set(o,newSql);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*@author lixiao
*@date 2023/4/27 10:37
*@Description: 修改多个
*/
public void test(){
Configuration configuration = sessionFactory.getConfiguration();
Collection<MappedStatement> mappedStatements = configuration.getMappedStatements();
Field[] declaredFields = this.getClass().getDeclaredFields();
List<String> strings = new ArrayList<>();
//这个时筛选要修改哪些sql做准备的,
for (Field declaredField : declaredFields) {
strings.add(declaredField.getType().getName());
}
//循环mappedStatements,修改里面的sql
for (Object mappedStatement1 : mappedStatements) {
try {
MappedStatement mappedStatement = null;
mappedStatement = (MappedStatement) mappedStatement1;
if (mappedStatement == null) {
continue;
}
if (!strings.contains(mappedStatement.getId().substring(0,mappedStatement.getId().lastIndexOf(".")))) {
continue;
}
RawSqlSource sqlSource = (RawSqlSource)mappedStatement.getSqlSource();
Field sqlSource1 = sqlSource.getClass().getDeclaredField("sqlSource");
sqlSource1.setAccessible(true);
Object o = sqlSource1.get(sqlSource);
Field sql1 = o.getClass().getDeclaredField("sql");
sql1.setAccessible(true);
BoundSql boundSql = sqlSource.getBoundSql(mappedStatement);
String sql = boundSql.getSql();
String newSql = sql.replace("cn", "en");
sql1.set(o,newSql);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
springboot动态修改mybatis的sql
于 2023-04-27 10:26:11 首次发布