package com.grm.util;
import com.grm.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 数据库操作工具类
*
* @author gaorimao
* @since 2021-12-29 09:32:48
*/
public class JdbcUtils {
/*
数据库配置信息username,password,driver,url最好写在properties文件中读取
*/
private static final String USERNAME = "root";
//数据库密码(本身不能明文写在项目中,此处简化了,先不考虑密码加密的问题)
private static final String PASSWORD = "root";
//驱动信息
private static final String DRIVER = "com.mysql.jdbc.Driver";
//数据库地址
private static final String URL = "jdbc:mysql://localhost:3306/mydb";
private Connection connection;
private PreparedStatement pstmt;
private ResultSet resultSet;
/**
* 利用构造方法初始化连接驱动,也可以用static静态代码块,都可以
*/
public JdbcUtils() {
try {
Class.forName(DRIVER);
} catch (Exception e) {
throw new BusinessException(500, "获取数据库连接驱动异常!");
}
}
/**
* 获得数据库的连接
*
* @return {@link Connection}
*/
public Connection getConnection() {
try {
connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (SQLException e) {
throw new BusinessException(500, "获取数据库连接异常!");
}
return connection;
}
/**
* 增加、删除、改
*
* @param sql sql
* @param params 参数
* @return boolean 是否成功
* @throws SQLException sql异常
*/
public boolean insertOrUpdateOrDelete(String sql, List<Object> params) throws SQLException {
boolean flag;
int result = -1;
pstmt = connection.prepareStatement(sql);
int index = 1;
if (params != null && !params.isEmpty()) {
for (int i = 0; i < params.size(); i++) {
pstmt.setObject(index++, params.get(i));
}
}
result = pstmt.executeUpdate();
flag = result > 0 ? true : false;
return flag;
}
/**
* 查询单条记录
*
* @param sql sql
* @param params 参数
* @return {@link Map<String, Object>}
* @throws SQLException sql异常
*/
public Map<String, Object> querySingle(String sql, List<Object> params) throws SQLException {
Map<String, Object> map = new HashMap<>();
int index = 1;
pstmt = connection.prepareStatement(sql);
if (params != null && !params.isEmpty()) {
for (int i = 0; i < params.size(); i++) {
pstmt.setObject(index++, params.get(i));
}
}
resultSet = pstmt.executeQuery();
ResultSetMetaData metaData = resultSet.getMetaData();
int colLen = metaData.getColumnCount();
while (resultSet.next()) {
for (int i = 0; i < colLen; i++) {
String colName = metaData.getColumnName(i + 1);
Object colValue = resultSet.getObject(colName);
colValue = (colValue == null ? "" : colValue);
map.put(colName, colValue);
}
}
return map;
}
/**
* 查询多条记录
*
* @param sql sql
* @param params 参数
* @return {@link List<Map<String, Object>>}
* @throws SQLException sql异常
*/
public List<Map<String, Object>> queryList(String sql, List<Object> params) throws SQLException {
List<Map<String, Object>> list = new ArrayList<>();
int index = 1;
pstmt = connection.prepareStatement(sql);
if (params != null && !params.isEmpty()) {
for (Object param : params) {
pstmt.setObject(index++, param);
}
}
resultSet = pstmt.executeQuery();
ResultSetMetaData metaData = resultSet.getMetaData();
int colLen = metaData.getColumnCount();
while (resultSet.next()) {
Map<String, Object> map = new HashMap<>();
for (int i = 0; i < colLen; i++) {
String colName = metaData.getColumnName(i + 1);
Object colValue = resultSet.getObject(colName);
colValue = (colValue == null ? "" : colValue);
map.put(colName, colValue);
}
list.add(map);
}
return list;
}
/**
* 通过反射机制查询单条记录
*
* @param sql sql
* @param params 参数
* @param cls cls
* @return {@link T}
* @throws Exception 异常
*/
public <T> T querySingle(String sql, List<Object> params,
Class<T> cls) throws Exception {
T resultObject = null;
int index = 1;
pstmt = connection.prepareStatement(sql);
if (params != null && !params.isEmpty()) {
for (int i = 0; i < params.size(); i++) {
pstmt.setObject(index++, params.get(i));
}
}
resultSet = pstmt.executeQuery();
ResultSetMetaData metaData = resultSet.getMetaData();
int colLen = metaData.getColumnCount();
while (resultSet.next()) {
// 通过反射机制创建一个实例
resultObject = cls.newInstance();
for (int i = 0; i < colLen; i++) {
String colName = metaData.getColumnName(i + 1);
Object colValue = resultSet.getObject(colName);
colValue = (colValue == null ? "" : colValue);
Field field = cls.getDeclaredField(colName);
// 打开javabean的访问权限
field.setAccessible(true);
field.set(resultObject, colValue);
}
}
return resultObject;
}
/**
* 通过反射机制查询多条记录
*
* @param sql sql
* @param params 参数
* @param cls cls
* @return {@link List<T>}
* @throws Exception 异常
*/
public <T> List<T> queryList(String sql, List<Object> params,
Class<T> cls) throws Exception {
List<T> list = new ArrayList<T>();
int index = 1;
pstmt = connection.prepareStatement(sql);
if (params != null && !params.isEmpty()) {
for (int i = 0; i < params.size(); i++) {
pstmt.setObject(index++, params.get(i));
}
}
resultSet = pstmt.executeQuery();
ResultSetMetaData metaData = resultSet.getMetaData();
int colLen = metaData.getColumnCount();
while (resultSet.next()) {
//通过反射机制创建一个实例
T resultObject = cls.newInstance();
for (int i = 0; i < colLen; i++) {
String colName = metaData.getColumnName(i + 1);
Object colValue = resultSet.getObject(colName);
colValue = (colValue == null ? "" : colValue);
Field field = cls.getDeclaredField(colName);
//打开javabean的访问权限
field.setAccessible(true);
field.set(resultObject, colValue);
}
list.add(resultObject);
}
return list;
}
/**
* 释放数据库连接
*/
public void close() {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
throw new BusinessException(500, "关闭数据库连接异常!");
}
}
}
}
其中业务异常类BusinessException
package com.grm.exception;
/**
* 业务异常类
*
* @author gaorimao
* @since 2021-12-26 18:38:37
*/
public class BusinessException extends RuntimeException {
private int code;
private String message;
public BusinessException(int code, String message) {
this.code = code;
this.message = message;
}
// getter setter
}
Springboot怎么捕获全局BusinessException呢
package com.grm.handler;
import com.grm.common.Result;
import com.grm.exception.BusinessException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;
import java.util.StringJoiner;
/**
* 自定义全局异常捕获
*
* @author gaorimao
*/
@RestControllerAdvice(annotations = RestController.class)
public class GlobalExceptionHandler {
/**
* 全局异常捕捉处理
*
* @param e 异常
* @return
*/
@ExceptionHandler(value = Exception.class)
public Result errorHandler(HttpServletRequest req, Exception e) {
return Result.failed(500, e.getMessage());
}
/**
* 全局异常捕捉处理
*
* @param e 异常
* @return
*/
@ExceptionHandler(value = BusinessException.class)
public Result businessExceptionHandler(HttpServletRequest req, Exception e) {
return Result.failed(500, e.getMessage());
}
}