
cn.cucc.utils.SqlUtils Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of jpaHelper Show documentation
Show all versions of jpaHelper Show documentation
spring-data-jpa增强工具包,简化 CRUD 操作
package cn.cucc.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import cn.hutool.core.util.StrUtil;
@Component
public class SqlUtils {
Logger logger = LoggerFactory.getLogger(this.getClass());
@Value("${spring.datasource.url:}")
String url;
@Value("${spring.datasource.printsql:true}")
Boolean printsql;
String separator = System.getProperty("line.separator");
public void logQuery(String sql) {
logQuery(sql, null);
}
public void logQuery(String sql, Object[] params) {
sql = formatSql(sql);
if (params != null) {
for (Object object : params) {
if (object instanceof String) {
sql = sql.replaceFirst("\\?", "'" + object.toString().replace("$", "¥").replace("\\%", "\\\\%") + "'");
} else {
sql = sql.replaceFirst("\\?", String.valueOf(object));
}
}
}
if (printsql) {
logger.info(separator + sql + separator);
}
}
public String formatSql(String sql) {
if (StrUtil.isEmpty(sql)) {
return "";
}
if (!url.contains("mysql")) {
sql = sql.replace("`", "\"");
}
sql = sql.replace("FROM", separator + "FROM")//
.replace("WHERE", separator + "WHERE")//
.replace("ORDER", separator + "ORDER")//
.replace("LIMIT", separator + "LIMIT")//
.replace("VALUES", separator + "VALUES");//
return sql;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy