Last active
May 25, 2025 15:24
-
-
Save groovelab/a367cedfd8fe51ba1ba850e68338b0db to your computer and use it in GitHub Desktop.
MyBatis delete data logger
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @Intercepts( | |
| Signature(type = Executor::class, method = "update", args = [MappedStatement::class, Any::class]), | |
| ) | |
| @Component | |
| class SqlDeleteInterceptor : Interceptor { | |
| private val logger = LoggerFactory.getLogger(SqlDeleteInterceptor::class.java) | |
| override fun intercept(invocation: Invocation): Any { | |
| loggingDeleteRowIfNeed(invocation) | |
| return invocation.proceed() | |
| } | |
| private fun loggingDeleteRowIfNeed(invocation: Invocation) { | |
| if (invocation.args.count() < 2) { | |
| return | |
| } | |
| val mappedStatement = invocation.args[0] as? MappedStatement ?: return | |
| if (mappedStatement.sqlCommandType != SqlCommandType.DELETE) { | |
| return | |
| } | |
| val parameter = invocation.args[1] | |
| val boundSql = mappedStatement.getBoundSql(parameter) | |
| val logPrefix = "Delete method: ${mappedStatement.id}." | |
| logger.info("$logPrefix SQL: ${boundSql.sql}, Parameters: $parameter") | |
| val connection = (invocation.target as? Executor)?.transaction?.connection ?: return | |
| val sql = boundSql.sql.replace("DELETE FROM", "SELECT * FROM") | |
| .let { | |
| if (it.contains("LIMIT")) it | |
| else "$it LIMIT 100" | |
| } | |
| val ps = connection.prepareStatement(sql) | |
| (parameter as? MapperMethod.ParamMap<*>)?.let { | |
| boundSql.parameterMappings.toList().forEachIndexed { i, parameterMapping -> | |
| ps.setObject(i + 1, parameter[parameterMapping.property].toString()) | |
| } | |
| } ?: run { | |
| parameter?.let { ps.setObject(1, it) } | |
| } | |
| try { | |
| ps.executeQuery().use { rs -> | |
| var rowCount = 0 | |
| while (rs.next()) { | |
| rowCount += 1 | |
| (1..rs.metaData.columnCount) | |
| .joinToString { rs.getString(it) ?: "" } | |
| .let { logger.info("$logPrefix Row: $it") } | |
| } | |
| if (rowCount == 0) { | |
| logger.info("$logPrefix Row: empty") | |
| } | |
| } | |
| } catch (e: SQLException) { | |
| logger.error("$logPrefix Error: ${e.message}", e) | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment