1、拦截器基础逻辑优化,使得过滤器、异常处理器、结果处理器使用更加方便

2、JdbcTemplate异常处理逻辑优化
This commit is contained in:
aoshiguchen
2022-06-30 13:44:51 +08:00
parent 3570839a1a
commit 650d9b65be
18 changed files with 536 additions and 213 deletions
@@ -21,7 +21,10 @@
*/
package fun.asgc.neutrino.core.aop;
import fun.asgc.neutrino.core.aop.interceptor.ExceptionHandler;
import fun.asgc.neutrino.core.aop.interceptor.Filter;
import fun.asgc.neutrino.core.aop.interceptor.Interceptor;
import fun.asgc.neutrino.core.aop.interceptor.ResultAdvice;
import java.lang.annotation.*;
@@ -35,7 +38,39 @@ import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface Intercept {
/**
* 指定拦截器
* @return
*/
Class<? extends Interceptor>[] value() default {};
/**
* 排除拦截器
* @return
*/
Class<? extends Interceptor>[] exclude() default {};
/**
* 忽略一切全局拦截器
* @return
*/
boolean ignoreGlobal() default false;
/**
* 指定过滤器
* @return
*/
Class<? extends Filter>[] filter() default {};
/**
* 指定异常处理器
* @return
*/
Class<? extends ExceptionHandler>[] exceptionHandler() default {};
/**
* 指定结果处理器
* @return
*/
Class<? extends ResultAdvice>[] resultAdvice() default {};
}
@@ -55,9 +55,10 @@ public class Invocation {
this.callback = callback;
this.args = args;
this.interceptors = InterceptorFactory.getListByTargetMethod(this.targetMethod);
this.returnValue = TypeUtil.getDefaultValue(this.targetMethod.getReturnType());
}
public void invoke() {
public void invoke() throws Exception {
if (CollectionUtil.notEmpty(this.interceptors) && index < this.interceptors.size()) {
this.interceptors.get(index++).intercept(this);
} else {
@@ -22,6 +22,7 @@
package fun.asgc.neutrino.core.aop.interceptor;
import fun.asgc.neutrino.core.aop.Invocation;
import fun.asgc.neutrino.core.util.Assert;
import fun.asgc.neutrino.core.util.CollectionUtil;
import fun.asgc.neutrino.core.util.TypeUtil;
import lombok.extern.slf4j.Slf4j;
@@ -36,59 +37,57 @@ import java.util.List;
*/
@Slf4j
public class InnerGlobalInterceptor implements Interceptor {
private static final List<Filter> filterList = new ArrayList<>();
private static final List<ResultAdvice> resultAdviceList = new ArrayList<>();
private static final List<ExceptionHandler> exceptionHandlerList = new ArrayList<>();
/**
* 拦截器包装器
*/
private static final InterceptorWrapper interceptorWrapper = new InterceptorWrapper(InnerGlobalInterceptor.class.getSimpleName());
@Override
public void intercept(Invocation inv) {
try {
log.debug("内置顶层拦截器 class:{} method:{} args:{} before", inv.getTargetClass().getName(), inv.getTargetMethod().getName(), inv.getArgs());
if (CollectionUtil.notEmpty(filterList)) {
for (Filter filter : filterList) {
if (filter.filtration(inv.getTargetClass(), inv.getTargetMethod(), inv.getArgs())) {
return;
}
}
}
inv.invoke();
Object result = inv.getReturnValue();
log.debug("内置顶层拦截器 class:{} method:{} args:{} result:{} after", inv.getTargetClass().getName(), inv.getTargetMethod().getName(), inv.getArgs(), result);
if (CollectionUtil.notEmpty(resultAdviceList)) {
for (ResultAdvice advice : resultAdviceList) {
result = advice.advice(inv.getTargetClass(), inv.getTargetMethod(), result);
}
}
if (null == result) {
result = TypeUtil.getDefaultValue(inv.getReturnType());
}
inv.setReturnValue(result);
log.debug("内置顶层拦截器 class:{} method:{} args:{} result:{} finished.", inv.getTargetClass().getName(), inv.getTargetMethod().getName(), inv.getArgs(), result);
} catch (Exception e) {
log.debug("内置顶层拦截器 class:{} method:{} args:{} exception.", inv.getTargetClass().getName(), inv.getTargetMethod().getName(), inv.getArgs());
if (CollectionUtil.notEmpty(exceptionHandlerList)) {
for (ExceptionHandler handler : exceptionHandlerList) {
if (handler.support(e)) {
Object result = handler.handle(e);
inv.setReturnValue(result);
return;
}
}
}
}
interceptorWrapper.intercept(inv);
}
/**
* 注册过滤器
* @param filter
*/
public static synchronized void registerFilter(Filter filter) {
filterList.add(filter);
interceptorWrapper.registerFilter(filter);
}
/**
* 注册过滤器
* @param filterList
*/
public static synchronized void registerFilter(List<Filter> filterList) {
interceptorWrapper.registerFilter(filterList);
}
/**
* 注册结果处理器
* @param resultAdvice
*/
public static synchronized void registerResultAdvice(ResultAdvice resultAdvice) {
resultAdviceList.add(resultAdvice);
interceptorWrapper.registerResultAdvice(resultAdvice);
}
/**
* 注册结果处理器
* @param resultAdviceList
*/
public static synchronized void registerResultAdvice(List<ResultAdvice> resultAdviceList) {
interceptorWrapper.registerResultAdvice(resultAdviceList);
}
/**
* 注册异常处理器
* @param exceptionHandler
*/
public static synchronized void registerExceptionHandler(ExceptionHandler exceptionHandler) {
exceptionHandlerList.add(exceptionHandler);
interceptorWrapper.registerExceptionHandler(exceptionHandler);
}
public static synchronized void registerExceptionHandler(List<ExceptionHandler> exceptionHandlerList) {
interceptorWrapper.registerExceptionHandler(exceptionHandlerList);
}
}
@@ -32,5 +32,5 @@ public interface Interceptor {
* 拦截方法
* @param inv
*/
void intercept(Invocation inv);
void intercept(Invocation inv) throws Exception;
}
@@ -28,6 +28,8 @@ import fun.asgc.neutrino.core.util.*;
import java.lang.reflect.Method;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* 拦截器工厂
@@ -38,29 +40,123 @@ public class InterceptorFactory {
private static final Cache<Class<? extends Interceptor>, Interceptor> interceptorCache = new MemoryCache<>();
private static final List<Interceptor> globalInterceptorList = Collections.synchronizedList(new ArrayList<>());
private static final Map<Method, List<Interceptor>> methodInterceptorListMap = new HashMap<>();
private static final Cache<Class<? extends Filter>, Filter> filterCache = new MemoryCache<>();
private static final Cache<Class<? extends ResultAdvice>, ResultAdvice> resultAdviceCache = new MemoryCache<>();
private static final Cache<Class<? extends ExceptionHandler>, ExceptionHandler> exceptionHandlerCache = new MemoryCache<>();
static {
registerGlobalInterceptor(InnerGlobalInterceptor.class);
}
public static <T extends Interceptor> T get(Class<T> clazz) {
return (T)LockUtil.doubleCheckProcess(() -> !interceptorCache.containsKey(clazz),
/**
* 获取或新建缓存bean实例
* @param clazz
* @param cache
* @param <T>
* @return
*/
private static <T> T getOrNewCacheBean(Class<T> clazz, Cache cache) {
return (T)LockUtil.doubleCheckProcess(() -> !cache.containsKey(clazz),
clazz,
() -> {
try {
if (BeanManager.getBean(clazz) != null) {
interceptorCache.set(clazz, BeanManager.getBean(clazz));
cache.set(clazz, BeanManager.getBean(clazz));
} else {
interceptorCache.set(clazz, clazz.newInstance());
cache.set(clazz, clazz.newInstance());
}
} catch (InstantiationException|IllegalAccessException e) {
throw new RuntimeException(e);
}
},
() -> interceptorCache.get(clazz)
() -> cache.get(clazz)
);
}
/**
* 获取拦截器实例
* @param clazz
* @param <T>
* @return
*/
public static <T extends Interceptor> T get(Class<? extends Interceptor> clazz) {
return (T)getOrNewCacheBean(clazz, interceptorCache);
}
/**
* 获取过滤器实例
* @param clazz
* @param <T>
* @return
*/
private static <T extends Filter> T getFilter(Class<? extends Filter> clazz) {
return (T)getOrNewCacheBean(clazz, filterCache);
}
/**
* 获取过滤器列表
* @param classes
* @param <T>
* @return
*/
private static <T extends Filter> List<T> getFilterList(Class<? extends Filter>[] classes) {
if (ArrayUtil.isEmpty(classes)) {
return null;
}
return Stream.of(classes).map(c -> (T)getFilter(c)).filter(Objects::nonNull).collect(Collectors.toList());
}
/**
* 获取结果处理器实例
* @param clazz
* @param <T>
* @return
*/
private static <T extends ResultAdvice> T getResultAdvice(Class<? extends ResultAdvice> clazz) {
return (T)getOrNewCacheBean(clazz, resultAdviceCache);
}
/**
* 获取结果处理器列表
* @param classes
* @param <T>
* @return
*/
private static <T extends ResultAdvice> List<T> getResultAdviceList(Class<? extends ResultAdvice>[] classes) {
if (ArrayUtil.isEmpty(classes)) {
return null;
}
return Stream.of(classes).map(c -> (T)getResultAdvice(c)).filter(Objects::nonNull).collect(Collectors.toList());
}
/**
* 获取异常处理器实例
* @param clazz
* @param <T>
* @return
*/
private static <T extends ExceptionHandler> T getExceptionHandler(Class<? extends ExceptionHandler> clazz) {
return (T)getOrNewCacheBean(clazz, exceptionHandlerCache);
}
/**
* 获取异常处理器列表
* @param classes
* @param <T>
* @return
*/
private static <T extends ExceptionHandler> List<T> getExceptionHandlerList(Class<? extends ExceptionHandler>[] classes) {
if (ArrayUtil.isEmpty(classes)) {
return null;
}
return Stream.of(classes).map(c -> (T)getExceptionHandler(c)).filter(Objects::nonNull).collect(Collectors.toList());
}
/**
* 获取目标方法的拦截器实例集合
* @param targetMethod
* @return
*/
public static List<Interceptor> getListByTargetMethod(Method targetMethod) {
Assert.notNull(targetMethod, "目标方法不能为空!");
@@ -69,6 +165,8 @@ public class InterceptorFactory {
() -> {
List<Interceptor> interceptors = new ArrayList<>();
interceptors.addAll(globalInterceptorList);
addInterceptorByAnnotation(interceptors, targetMethod.getDeclaringClass().getAnnotation(Intercept.class));
addInterceptorByAnnotation(interceptors, targetMethod.getAnnotation(Intercept.class));
// 如果被代理方法所属类是一个接口,那么该接口所有继承接口链路上的注解都对该方法生效
if (ClassUtil.isInterface(targetMethod.getDeclaringClass())) {
List<Class<?>> interfaceList = ReflectUtil.getInterfaceAll(targetMethod.getDeclaringClass());
@@ -78,13 +176,16 @@ public class InterceptorFactory {
}
}
}
addInterceptorByAnnotation(interceptors, targetMethod.getDeclaringClass().getAnnotation(Intercept.class));
addInterceptorByAnnotation(interceptors, targetMethod.getAnnotation(Intercept.class));
methodInterceptorListMap.put(targetMethod, interceptors);
},
() -> methodInterceptorListMap.get(targetMethod));
}
/**
* 根据拦截器注解,将拦截器添加到拦截器集合中
* @param interceptors
* @param intercept
*/
private static void addInterceptorByAnnotation(List<Interceptor> interceptors, Intercept intercept) {
if (null == interceptors || null == intercept) {
return;
@@ -105,6 +206,22 @@ public class InterceptorFactory {
}
}
}
if (ArrayUtil.notEmpty(intercept.filter()) || ArrayUtil.notEmpty(intercept.resultAdvice()) || ArrayUtil.notEmpty(intercept.exceptionHandler())) {
InterceptorWrapper wrapper = new InterceptorWrapper();
List<Filter> filterList = getFilterList(intercept.filter());
List<ResultAdvice> resultAdviceList = getResultAdviceList(intercept.resultAdvice());
List<ExceptionHandler> exceptionHandlerList = getExceptionHandlerList(intercept.exceptionHandler());
if (CollectionUtil.notEmpty(filterList)) {
wrapper.registerFilter(filterList);
}
if (CollectionUtil.notEmpty(resultAdviceList)) {
wrapper.registerResultAdvice(resultAdviceList);
}
if (CollectionUtil.notEmpty(exceptionHandlerList)) {
wrapper.registerExceptionHandler(exceptionHandlerList);
}
interceptors.add(wrapper);
}
if (intercept.ignoreGlobal()) {
interceptors.removeAll(globalInterceptorList);
}
@@ -0,0 +1,144 @@
/**
* Copyright (c) 2022 aoshiguchen
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package fun.asgc.neutrino.core.aop.interceptor;
import fun.asgc.neutrino.core.aop.Invocation;
import fun.asgc.neutrino.core.util.Assert;
import fun.asgc.neutrino.core.util.CollectionUtil;
import fun.asgc.neutrino.core.util.TypeUtil;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.List;
/**
* 拦截器的包装器
* @author: aoshiguchen
* @date: 2022/6/30
*/
@Slf4j
public class InterceptorWrapper implements Interceptor {
private final List<Filter> filterList = new ArrayList<>();
private final List<ResultAdvice> resultAdviceList = new ArrayList<>();
private final List<ExceptionHandler> exceptionHandlerList = new ArrayList<>();
private String name;
public InterceptorWrapper() {
this.name = this.getClass().getSimpleName();
}
public InterceptorWrapper(String name) {
this.name = name;
}
@Override
public void intercept(Invocation inv) {
try {
log.debug("拦截器:{} class:{} method:{} args:{} before", this.name, inv.getTargetClass().getName(), inv.getTargetMethod().getName(), inv.getArgs());
if (CollectionUtil.notEmpty(filterList)) {
for (Filter filter : filterList) {
if (filter.filtration(inv.getTargetClass(), inv.getTargetMethod(), inv.getArgs())) {
return;
}
}
}
inv.invoke();
Object result = inv.getReturnValue();
log.debug("拦截器:{} class:{} method:{} args:{} result:{} after", this.name, inv.getTargetClass().getName(), inv.getTargetMethod().getName(), inv.getArgs(), result);
if (CollectionUtil.notEmpty(resultAdviceList)) {
for (ResultAdvice advice : resultAdviceList) {
result = advice.advice(inv.getTargetClass(), inv.getTargetMethod(), result);
}
}
if (null == result) {
result = TypeUtil.getDefaultValue(inv.getReturnType());
}
inv.setReturnValue(result);
log.debug("拦截器:{} class:{} method:{} args:{} result:{} finished.", this.name, inv.getTargetClass().getName(), inv.getTargetMethod().getName(), inv.getArgs(), result);
} catch (Exception e) {
log.debug("拦截器:{} class:{} method:{} args:{} exception.", this.name, inv.getTargetClass().getName(), inv.getTargetMethod().getName(), inv.getArgs());
if (CollectionUtil.notEmpty(exceptionHandlerList)) {
for (ExceptionHandler handler : exceptionHandlerList) {
if (handler.support(e)) {
Object result = handler.handle(e);
if (null != result) {
inv.setReturnValue(result);
}
return;
}
}
}
}
}
/**
* 注册过滤器
* @param filter
*/
public synchronized void registerFilter(Filter filter) {
Assert.notNull(filter, "过滤器不能为空!");
this.filterList.add(filter);
}
/**
* 注册过滤器
* @param filterList
*/
public synchronized void registerFilter(List<Filter> filterList) {
Assert.notEmpty(filterList, "过滤器不能为空!");
this.filterList.addAll(filterList);
}
/**
* 注册结果处理器
* @param resultAdvice
*/
public synchronized void registerResultAdvice(ResultAdvice resultAdvice) {
Assert.notNull(resultAdvice, "结果处理器不能为空!");
this.resultAdviceList.add(resultAdvice);
}
/**
* 注册结果处理器
* @param resultAdviceList
*/
public synchronized void registerResultAdvice(List<ResultAdvice> resultAdviceList) {
Assert.notEmpty(resultAdviceList, "结果处理器不能为空!");
this.resultAdviceList.addAll(resultAdviceList);
}
/**
* 注册异常处理器
* @param exceptionHandler
*/
public synchronized void registerExceptionHandler(ExceptionHandler exceptionHandler) {
Assert.notNull(exceptionHandler, "异常处理器不能为空!");
this.exceptionHandlerList.add(exceptionHandler);
}
public synchronized void registerExceptionHandler(List<ExceptionHandler> exceptionHandlerList) {
Assert.notEmpty(exceptionHandlerList, "异常处理器不能为空!");
this.exceptionHandlerList.addAll(exceptionHandlerList);
}
}
@@ -22,6 +22,7 @@
package fun.asgc.neutrino.core.db.dao;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.List;
/**
@@ -37,7 +38,7 @@ public interface Dao<T> {
* @param po
* @return
*/
T add(T po);
T add(T po) throws SQLException;
//==============================================修改=====================
@@ -70,13 +71,13 @@ public interface Dao<T> {
int delete();
//==============================================查询=====================
Long count();
Long count(T po, String ...field);
Long count() throws SQLException;
Long count(T po, String ...field) throws SQLException;
T findOneById(Serializable id);
T findOne(T po, String ...field);
List<T> find();
List<T> find(T po, String ...field);
T findOneById(Serializable id) throws SQLException;
T findOne(T po, String ...field) throws SQLException;
List<T> find() throws SQLException;
List<T> find(T po, String ...field) throws SQLException;
List<T> findPage(int beginNo, int pageSize);
List<T> findPage(T po,int beginNo, int pageSize, String ...field);
@@ -35,6 +35,7 @@ import fun.asgc.neutrino.core.util.ReflectUtil;
import javax.sql.DataSource;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.sql.SQLException;
import java.util.*;
/**
@@ -88,7 +89,7 @@ public class DefaultDaoImpl<T> implements Dao<T> {
}
@Override
public T add(T po) {
public T add(T po) throws SQLException {
SqlAndParams sqlAndParams = this.sqlDialect.add(po);
jdbcTemplate.update(sqlAndParams.getSql());
Serializable idValue = getIdValue(po);
@@ -109,13 +110,13 @@ public class DefaultDaoImpl<T> implements Dao<T> {
}
@Override
public Long count() {
public Long count() throws SQLException {
SqlAndParams sqlAndParams = this.sqlDialect.count(entryClass, null);
return jdbcTemplate.queryForLong(sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
@Override
public Long count(T po, String... field) {
public Long count(T po, String... field) throws SQLException {
Set<String> filter = Sets.newHashSet(field);
Cache<Field, String> fieldCache = DbCache.getFieldCache(entryClass);
SqlAndParams sqlAndParams = this.sqlDialect.count(entryClass, new LinkedHashMap<String, Object>(){
@@ -132,7 +133,7 @@ public class DefaultDaoImpl<T> implements Dao<T> {
}
@Override
public T findOneById(Serializable id) {
public T findOneById(Serializable id) throws SQLException {
SqlAndParams sqlAndParams = this.sqlDialect.find(entryClass, new LinkedHashMap<String, Object>(){
{
this.put(idColumnName, id);
@@ -142,7 +143,7 @@ public class DefaultDaoImpl<T> implements Dao<T> {
}
@Override
public T findOne(T po, String... field) {
public T findOne(T po, String... field) throws SQLException {
Set<String> filter = Sets.newHashSet(field);
Cache<Field, String> fieldCache = DbCache.getFieldCache(entryClass);
SqlAndParams sqlAndParams = this.sqlDialect.find(entryClass, new LinkedHashMap<String, Object>(){
@@ -159,13 +160,13 @@ public class DefaultDaoImpl<T> implements Dao<T> {
}
@Override
public List<T> find() {
public List<T> find() throws SQLException {
SqlAndParams sqlAndParams = this.sqlDialect.find(entryClass, null);
return jdbcTemplate.queryForList(entryClass, sqlAndParams);
}
@Override
public List<T> find(T po, String... field) {
public List<T> find(T po, String... field) throws SQLException {
Set<String> filter = Sets.newHashSet(field);
Cache<Field, String> fieldCache = DbCache.getFieldCache(entryClass);
SqlAndParams sqlAndParams = this.sqlDialect.find(entryClass, new LinkedHashMap<String, Object>(){
@@ -34,6 +34,7 @@ import lombok.Data;
import lombok.experimental.Accessors;
import java.lang.reflect.Method;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Map;
@@ -50,12 +51,13 @@ public class SqlMapperInterceptor implements Interceptor {
private static final Cache<Method, Params> paramsCache = new MemoryCache<>();
@Override
public void intercept(Invocation inv) {
public void intercept(Invocation inv) throws SQLException {
Assert.notNull(jdbcTemplate, "JdbcTemplate未注入,调用失败!");
Params params = getParams(inv.getTargetMethod());
if (null == params) {
return;
}
String sql = params.getSql();
Class<?> resultType = params.getResultType();
Object res = null;
@@ -21,6 +21,8 @@
*/
package fun.asgc.neutrino.core.db.template;
import java.sql.SQLException;
/**
* @author: aoshiguchen
* @date: 2022/6/27
@@ -31,6 +33,6 @@ public interface JdbcCallback<T> {
* 执行
* @return
*/
T execute();
T execute() throws SQLException;
}
@@ -53,15 +53,8 @@ public class JdbcOperations {
* @param <T>
* @return
*/
public <T> T execute(JdbcCallback<T> callback) {
T res = null;
try {
res = callback.execute();
} catch (Exception e) {
throw new RuntimeException(e);
}
return res;
public <T> T execute(JdbcCallback<T> callback) throws SQLException {
return callback.execute();
}
/**
@@ -71,17 +64,11 @@ public class JdbcOperations {
* @param params
* @return
*/
public int executeUpdate(final Connection conn , final String sql, final Object[] params) {
public int executeUpdate(final Connection conn , final String sql, final Object[] params) throws SQLException {
return this.execute(new PreparedStatementJdbcCallback<Integer>(){
@Override
public Integer execute(PreparedStatement ps) {
int res = -1;
try{
res = ps.executeUpdate();
}catch(SQLException e){
throw new RuntimeException(e);
}
return res;
public Integer execute(PreparedStatement ps) throws SQLException {
return ps.executeUpdate();
}
@Override
public Object[] getParams() {
@@ -107,7 +94,7 @@ public class JdbcOperations {
* @param <T>
* @return
*/
public <T> T executeQuery(final Connection conn,final Class<T> clazz,final String sql,final Object[] params) {
public <T> T executeQuery(final Connection conn,final Class<T> clazz,final String sql,final Object[] params) throws SQLException {
return this.execute(new PreparedStatementJdbcCallback<T>() {
@Override
@@ -172,7 +159,7 @@ public class JdbcOperations {
* @param <T>
* @return
*/
public <T> List<T> executeQueryForList(final Connection conn, final Class<T> clazz, final String sql, final Object[] params) {
public <T> List<T> executeQueryForList(final Connection conn, final Class<T> clazz, final String sql, final Object[] params) throws SQLException {
return this.execute(new PreparedStatementJdbcCallback<List<T>>() {
@Override
public List<T> execute(PreparedStatement ps) {
@@ -52,15 +52,13 @@ public class JdbcTemplate {
this.jdbcOperations = JdbcOperations.getInstance();
}
public int update(String sql, Object ...params){
public int update(String sql, Object ...params) throws SQLException {
int res = -1;
Connection conn = null;
try {
conn = dataSourceHolder.getConnection();
res = jdbcOperations.executeUpdate(conn,sql, params);
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
try {
dataSourceHolder.tryClose(conn);
@@ -72,27 +70,25 @@ public class JdbcTemplate {
return res;
}
public int update(SqlAndParams sqlAndParams) {
public int update(SqlAndParams sqlAndParams) throws SQLException {
return update(sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
public int updateByMap(String sql, Map<String,Object> params){
public int updateByMap(String sql, Map<String,Object> params) throws SQLException {
return update(new SqlAndParams(sql, params));
}
public int updateByModel(String sql, Object model){
public int updateByModel(String sql, Object model) throws SQLException {
return update(new SqlAndParams(sql, model));
}
public <T> T query(Class<T> clazz, String sql, Object ...params){
public <T> T query(Class<T> clazz, String sql, Object ...params) throws SQLException {
T res = null;
Connection conn = null;
try {
conn = dataSourceHolder.getConnection();
res = jdbcOperations.executeQuery(conn, clazz,sql, params);
} catch (SQLException e) {
new RuntimeException(e);
} finally {
try {
dataSourceHolder.tryClose(conn);
@@ -104,167 +100,165 @@ public class JdbcTemplate {
return res;
}
public <T> T query(Class<T> clazz, SqlAndParams sqlAndParams) {
public <T> T query(Class<T> clazz, SqlAndParams sqlAndParams) throws SQLException {
return query(clazz, sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
public <T> T queryByMap(Class<T> clazz, String sql, Map<String,Object> params){
public <T> T queryByMap(Class<T> clazz, String sql, Map<String,Object> params) throws SQLException {
return query(clazz, new SqlAndParams(sql, params));
}
public <T> T queryByModel(Class<T> clazz, String sql, Object model){
public <T> T queryByModel(Class<T> clazz, String sql, Object model) throws SQLException {
return query(clazz, new SqlAndParams(sql, model));
}
public byte queryForByteByMap(String sql, Map<String,Object> params){
public byte queryForByteByMap(String sql, Map<String,Object> params) throws SQLException {
SqlAndParams sqlAndParams = new SqlAndParams(sql, params);
return queryForByte(sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
public byte queryForByteByModel(String sql, Object model){
public byte queryForByteByModel(String sql, Object model) throws SQLException {
SqlAndParams sqlAndParams = new SqlAndParams(sql, model);
return queryForByte(sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
public byte queryForByte(String sql, Object ...params){
public byte queryForByte(String sql, Object ...params) throws SQLException {
return query(byte.class, sql, params);
}
public short queryForShortByMap(String sql, Map<String,Object> params){
public short queryForShortByMap(String sql, Map<String,Object> params) throws SQLException {
SqlAndParams sqlAndParams = new SqlAndParams(sql, params);
return queryForShort(sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
public short queryForShortByModel(String sql, Object model){
public short queryForShortByModel(String sql, Object model) throws SQLException {
SqlAndParams sqlAndParams = new SqlAndParams(sql, model);
return queryForShort(sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
public short queryForShort(String sql, Object ...params){
public short queryForShort(String sql, Object ...params) throws SQLException {
return query(short.class, sql, params);
}
public int queryForIntByMap(String sql, Map<String,Object> params){
public int queryForIntByMap(String sql, Map<String,Object> params) throws SQLException {
SqlAndParams sqlAndParams = new SqlAndParams(sql, params);
return queryForInt(sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
public int queryForIntByModel(String sql, Object model){
public int queryForIntByModel(String sql, Object model) throws SQLException {
SqlAndParams sqlAndParams = new SqlAndParams(sql, model);
return queryForInt(sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
public int queryForInt(String sql, Object ...params){
public int queryForInt(String sql, Object ...params) throws SQLException {
return query(int.class, sql, params);
}
public Long queryForLongByMap(String sql, Map<String,Object> params){
public Long queryForLongByMap(String sql, Map<String,Object> params) throws SQLException {
SqlAndParams sqlAndParams = new SqlAndParams(sql, params);
return queryForLong(sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
public Long queryForLongByModel(String sql, Object model){
public Long queryForLongByModel(String sql, Object model) throws SQLException {
SqlAndParams sqlAndParams = new SqlAndParams(sql, model);
return queryForLong(sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
public Long queryForLong(String sql,Object ...params){
public Long queryForLong(String sql,Object ...params) throws SQLException {
return query(long.class, sql, params);
}
public float queryForFloatByMap(String sql, Map<String,Object> params){
public float queryForFloatByMap(String sql, Map<String,Object> params) throws SQLException {
SqlAndParams sqlAndParams = new SqlAndParams(sql, params);
return queryForFloat(sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
public float queryForFloatByModel(String sql, Object model){
public float queryForFloatByModel(String sql, Object model) throws SQLException {
SqlAndParams sqlAndParams = new SqlAndParams(sql, model);
return queryForFloat(sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
public float queryForFloat(String sql,Object ...params){
public float queryForFloat(String sql,Object ...params) throws SQLException {
return query(float.class, sql, params);
}
public double queryForDoubleByMap(String sql, Map<String,Object> params){
public double queryForDoubleByMap(String sql, Map<String,Object> params) throws SQLException {
SqlAndParams sqlAndParams = new SqlAndParams(sql, params);
return queryForDouble(sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
public double queryForDoubleByModel(String sql, Object model){
public double queryForDoubleByModel(String sql, Object model) throws SQLException {
SqlAndParams sqlAndParams = new SqlAndParams(sql, model);
return queryForDouble(sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
public double queryForDouble(String sql, Object ...params){
public double queryForDouble(String sql, Object ...params) throws SQLException {
return query(double.class, sql, params);
}
public char queryForCharByMap(String sql, Map<String,Object> params){
public char queryForCharByMap(String sql, Map<String,Object> params) throws SQLException {
SqlAndParams sqlAndParams = new SqlAndParams(sql, params);
return queryForChar(sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
public char queryForCharByModel(String sql, Object model){
public char queryForCharByModel(String sql, Object model) throws SQLException {
SqlAndParams sqlAndParams = new SqlAndParams(sql, model);
return queryForChar(sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
public char queryForChar(String sql, Object ...params){
public char queryForChar(String sql, Object ...params) throws SQLException {
return query(char.class, sql, params);
}
public boolean queryForBooleanByMap(String sql, Map<String,Object> params){
public boolean queryForBooleanByMap(String sql, Map<String,Object> params) throws SQLException {
SqlAndParams sqlAndParams = new SqlAndParams(sql, params);
return queryForBoolean(sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
public boolean queryForBooleanByModel(String sql, Object model){
public boolean queryForBooleanByModel(String sql, Object model) throws SQLException {
SqlAndParams sqlAndParams = new SqlAndParams(sql, model);
return queryForBoolean(sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
public boolean queryForBoolean(String sql, Object ...params){
public boolean queryForBoolean(String sql, Object ...params) throws SQLException {
return query(boolean.class, sql, params);
}
public String queryForStringByMap(String sql, Map<String,Object> params){
public String queryForStringByMap(String sql, Map<String,Object> params) throws SQLException {
SqlAndParams sqlAndParams = new SqlAndParams(sql, params);
return queryForString(sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
public String queryForStringByModel(String sql, Object model){
public String queryForStringByModel(String sql, Object model) throws SQLException {
SqlAndParams sqlAndParams = new SqlAndParams(sql, model);
return queryForString(sql, sqlAndParams.getParamArray());
}
public String queryForString(String sql, Object ...params){
public String queryForString(String sql, Object ...params) throws SQLException {
return query(String.class, sql, params);
}
public Map<String,Object> queryForMapByMap(String sql, Map<String,Object> params){
public Map<String,Object> queryForMapByMap(String sql, Map<String,Object> params) throws SQLException {
SqlAndParams sqlAndParams = new SqlAndParams(sql, params);
return queryForMap(sql, sqlAndParams.getParamArray());
}
public Map<String,Object> queryForMapByModel(String sql, Object model){
public Map<String,Object> queryForMapByModel(String sql, Object model) throws SQLException {
SqlAndParams sqlAndParams = new SqlAndParams(sql, model);
return queryForMap(sql, sqlAndParams.getParamArray());
}
public Map<String,Object> queryForMap(String sql, Object ...params){
public Map<String,Object> queryForMap(String sql, Object ...params) throws SQLException {
return (Map<String,Object>)query(HashMap.class, sql, params);
}
public <T> List<T> queryForList(Class<T> clazz, String sql, Object ...params){
public <T> List<T> queryForList(Class<T> clazz, String sql, Object ...params) throws SQLException {
List<T> res = null;
Connection conn = null;
try {
conn = dataSourceHolder.getConnection();
res = jdbcOperations.executeQueryForList(conn, clazz, sql, params);
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
try {
dataSourceHolder.tryClose(conn);
@@ -276,156 +270,156 @@ public class JdbcTemplate {
return res;
}
public <T> List<T> queryForList(Class<T> clazz, SqlAndParams sqlAndParams) {
public <T> List<T> queryForList(Class<T> clazz, SqlAndParams sqlAndParams) throws SQLException {
return queryForList(clazz, sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
public <T> List<T> queryForListByMap(Class<T> clazz, String sql, Map<String,Object> params){
public <T> List<T> queryForListByMap(Class<T> clazz, String sql, Map<String,Object> params) throws SQLException {
SqlAndParams sqlAndParams = new SqlAndParams(sql, params);
return queryForList(clazz, sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
public <T> List<T> queryForListByModel(Class<T> clazz, String sql, Object model){
public <T> List<T> queryForListByModel(Class<T> clazz, String sql, Object model) throws SQLException {
SqlAndParams sqlAndParams = new SqlAndParams(sql, model);
return queryForList(clazz, sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
public List<Byte> queryForListByteByMap(String sql, Map<String,Object> params){
public List<Byte> queryForListByteByMap(String sql, Map<String,Object> params) throws SQLException {
SqlAndParams sqlAndParams = new SqlAndParams(sql, params);
return queryForListByte(sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
public List<Byte> queryForListByteByModel(String sql, Object model){
public List<Byte> queryForListByteByModel(String sql, Object model) throws SQLException {
SqlAndParams sqlAndParams = new SqlAndParams(sql, model);
return queryForListByte(sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
public List<Byte> queryForListByte(String sql,Object ...params){
public List<Byte> queryForListByte(String sql,Object ...params) throws SQLException {
return queryForList(byte.class, sql,params);
}
public List<Short> queryForListShortByMap(String sql, Map<String, Object> params){
public List<Short> queryForListShortByMap(String sql, Map<String, Object> params) throws SQLException {
SqlAndParams sqlAndParams = new SqlAndParams(sql, params);
return queryForListShort(sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
public List<Short> queryForListShortByModel(String sql, Object model){
public List<Short> queryForListShortByModel(String sql, Object model) throws SQLException {
SqlAndParams sqlAndParams = new SqlAndParams(sql, model);
return queryForListShort(sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
public List<Short> queryForListShort(String sql, Object ...params){
public List<Short> queryForListShort(String sql, Object ...params) throws SQLException {
return queryForList(short.class, sql, params);
}
public List<Integer> queryForListIntByMap(String sql, Map<String,Object> params){
public List<Integer> queryForListIntByMap(String sql, Map<String,Object> params) throws SQLException {
SqlAndParams sqlAndParams = new SqlAndParams(sql, params);
return queryForListInt(sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
public List<Integer> queryForListIntByModel(String sql, Object model){
public List<Integer> queryForListIntByModel(String sql, Object model) throws SQLException {
SqlAndParams sqlAndParams = new SqlAndParams(sql, model);
return queryForListInt(sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
public List<Integer> queryForListInt(String sql, Object ...params){
public List<Integer> queryForListInt(String sql, Object ...params) throws SQLException {
return queryForList(int.class, sql, params);
}
public List<Long> queryForListLongByMap(String sql, Map<String,Object> params){
public List<Long> queryForListLongByMap(String sql, Map<String,Object> params) throws SQLException {
SqlAndParams sqlAndParams = new SqlAndParams(sql, params);
return queryForListLong(sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
public List<Long> queryForListLongByModel(String sql, Object model){
public List<Long> queryForListLongByModel(String sql, Object model) throws SQLException {
SqlAndParams sqlAndParams = new SqlAndParams(sql, model);
return queryForListLong(sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
public List<Long> queryForListLong(String sql,Object ...params){
public List<Long> queryForListLong(String sql,Object ...params) throws SQLException {
return queryForList(long.class, sql, params);
}
public List<Float> queryForListFloatByMap(String sql, Map<String,Object> params){
public List<Float> queryForListFloatByMap(String sql, Map<String,Object> params) throws SQLException {
SqlAndParams sqlAndParams = new SqlAndParams(sql, params);
return queryForListFloat(sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
public List<Float> queryForListFloatByModel(String sql, Object model){
public List<Float> queryForListFloatByModel(String sql, Object model) throws SQLException {
SqlAndParams sqlAndParams = new SqlAndParams(sql, model);
return queryForListFloat(sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
public List<Float> queryForListFloat(String sql, Object ...params){
public List<Float> queryForListFloat(String sql, Object ...params) throws SQLException {
return queryForList(float.class, sql, params);
}
public List<Double> queryForListDoubleByMap(String sql ,Map<String,Object> params){
public List<Double> queryForListDoubleByMap(String sql ,Map<String,Object> params) throws SQLException {
SqlAndParams sqlAndParams = new SqlAndParams(sql, params);
return queryForListDouble(sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
public List<Double> queryForListDoubleByModel(String sql, Object model){
public List<Double> queryForListDoubleByModel(String sql, Object model) throws SQLException {
SqlAndParams sqlAndParams = new SqlAndParams(sql, model);
return queryForListDouble(sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
public List<Double> queryForListDouble(String sql, Object ...params){
public List<Double> queryForListDouble(String sql, Object ...params) throws SQLException {
return queryForList(double.class, sql, params);
}
public List<Character> queryForListCharByMap(String sql, Map<String,Object> params){
public List<Character> queryForListCharByMap(String sql, Map<String,Object> params) throws SQLException {
SqlAndParams sqlAndParams = new SqlAndParams(sql, params);
return queryForListChar(sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
public List<Character> queryForListCharByModel(String sql, Object model){
public List<Character> queryForListCharByModel(String sql, Object model) throws SQLException {
SqlAndParams sqlAndParams = new SqlAndParams(sql, model);
return queryForListChar(sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
public List<Character> queryForListChar(String sql, Object ...params){
public List<Character> queryForListChar(String sql, Object ...params) throws SQLException {
return queryForList(char.class, sql, params);
}
public List<Boolean> queryForListBooleanByMap(String sql, Map<String,Object> params){
public List<Boolean> queryForListBooleanByMap(String sql, Map<String,Object> params) throws SQLException {
SqlAndParams sqlAndParams = new SqlAndParams(sql, params);
return queryForListBoolean(sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
public List<Boolean> queryForListBooleanByModel(String sql, Object model){
public List<Boolean> queryForListBooleanByModel(String sql, Object model) throws SQLException {
SqlAndParams sqlAndParams = new SqlAndParams(sql, model);
return queryForListBoolean(sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
public List<Boolean> queryForListBoolean(String sql, Object ...params){
public List<Boolean> queryForListBoolean(String sql, Object ...params) throws SQLException {
return queryForList(boolean.class, sql, params);
}
public List<String> queryForListStringByMap(String sql, Map<String,Object> params){
public List<String> queryForListStringByMap(String sql, Map<String,Object> params) throws SQLException {
SqlAndParams sqlAndParams = new SqlAndParams(sql, params);
return queryForListString(sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
public List<String> queryForListStringByModel(String sql, Object model){
public List<String> queryForListStringByModel(String sql, Object model) throws SQLException {
SqlAndParams sqlAndParams = new SqlAndParams(sql, model);
return queryForListString(sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
public List<String> queryForListString(String sql, Object ...params){
public List<String> queryForListString(String sql, Object ...params) throws SQLException {
return queryForList(String.class, sql, params);
}
public List<Map> queryForListMap(String sql, Object ...params){
public List<Map> queryForListMap(String sql, Object ...params) throws SQLException {
return queryForList(Map.class, sql, params);
}
public List<Map> queryForListMapByMap(String sql, Map<String,Object> params){
public List<Map> queryForListMapByMap(String sql, Map<String,Object> params) throws SQLException {
SqlAndParams sqlAndParams = new SqlAndParams(sql, params);
return queryForListMap(sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
public List<Map> queryForListMapByModel(String sql, Object model){
public List<Map> queryForListMapByModel(String sql, Object model) throws SQLException {
SqlAndParams sqlAndParams = new SqlAndParams(sql, model);
return queryForListMap(sqlAndParams.getSql(), sqlAndParams.getParamArray());
}
@@ -26,6 +26,7 @@ import lombok.extern.slf4j.Slf4j;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
*
@@ -36,35 +37,32 @@ import java.sql.PreparedStatement;
public abstract class PreparedStatementJdbcCallback<T> implements JdbcCallback<T> {
@Override
public T execute() {
public T execute() throws SQLException {
PreparedStatement pstm = null;
Object[] params = this.getParams();
Connection conn = getConnection();
T res = null;
try {
log.debug("sql:" + this.getSql());
StringBuffer sb = new StringBuffer();
if (ArrayUtil.notEmpty(params)) {
for(Object o : params){
sb.append(o.toString()).append(",");
}
if(sb.length() > 0 && sb.charAt(sb.length() - 1) == ','){
sb.deleteCharAt(sb.length() - 1);
}
log.debug("sql:" + this.getSql());
StringBuffer sb = new StringBuffer();
if (ArrayUtil.notEmpty(params)) {
for(Object o : params){
sb.append(o.toString()).append(",");
}
log.debug("params:" + sb.toString());
pstm = conn.prepareStatement(this.getSql());
if (ArrayUtil.notEmpty(params)) {
for(int i = 0;i < params.length;i++){
pstm.setObject(i + 1, params[i]);
}
if(sb.length() > 0 && sb.charAt(sb.length() - 1) == ','){
sb.deleteCharAt(sb.length() - 1);
}
res = this.execute(pstm);
} catch (Exception e) {
throw new RuntimeException(e);
}
log.debug("params:" + sb.toString());
pstm = conn.prepareStatement(this.getSql());
if (ArrayUtil.notEmpty(params)) {
for(int i = 0;i < params.length;i++){
pstm.setObject(i + 1, params[i]);
}
}
res = this.execute(pstm);
return res;
}
@@ -86,7 +84,7 @@ public abstract class PreparedStatementJdbcCallback<T> implements JdbcCallback<T
* @param ps
* @return
*/
abstract T execute(PreparedStatement ps);
abstract T execute(PreparedStatement ps) throws SQLException;
/**
* 获取数据库连接
@@ -33,7 +33,7 @@ import lombok.extern.slf4j.Slf4j;
public class GlobalInterceptor implements Interceptor {
@Override
public void intercept(Invocation inv) {
public void intercept(Invocation inv) throws Exception {
log.info("全局拦截器1 class:{} method:{} args:{} before", inv.getTargetClass().getName(), inv.getTargetMethod().getName(), inv.getArgs());
inv.invoke();
log.info("全局拦截器1 class:{} method:{} args:{} after", inv.getTargetClass().getName(), inv.getTargetMethod().getName(), inv.getArgs());
@@ -29,6 +29,7 @@ import lombok.ToString;
import lombok.experimental.Accessors;
import org.junit.Test;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
@@ -50,7 +51,7 @@ public class DaoTest {
}
@Test
public void add() {
public void add() throws SQLException {
Dao<User> userDao = new DefaultDaoImpl<>(dataSource, dbType, User.class);
User user = new User();
user.setId(4L);
@@ -63,14 +64,14 @@ public class DaoTest {
}
@Test
public void findOneById() {
public void findOneById() throws SQLException {
Dao<User> userDao = new DefaultDaoImpl<>(dataSource, dbType, User.class);
User user = userDao.findOneById(3);
System.out.println(user);
}
@Test
public void findOne1() {
public void findOne1() throws SQLException {
Dao<User> userDao = new DefaultDaoImpl<>(dataSource, dbType, User.class);
User user = userDao.findOne(new User()
.setId(1L), "id");
@@ -78,7 +79,7 @@ public class DaoTest {
}
@Test
public void findOne2() {
public void findOne2() throws SQLException {
Dao<User> userDao = new DefaultDaoImpl<>(dataSource, dbType, User.class);
User user = userDao.findOne(new User()
.setAge(23), "age");
@@ -86,7 +87,7 @@ public class DaoTest {
}
@Test
public void findOne3() {
public void findOne3() throws SQLException {
Dao<User> userDao = new DefaultDaoImpl<>(dataSource, dbType, User.class);
User user = userDao.findOne(new User()
.setAge(23)
@@ -95,27 +96,27 @@ public class DaoTest {
}
@Test
public void find1() {
public void find1() throws SQLException {
Dao<User> userDao = new DefaultDaoImpl<>(dataSource, dbType, User.class);
List<User> userList = userDao.find();
System.out.println(userList);
}
@Test
public void find2() {
public void find2() throws SQLException {
Dao<User> userDao = new DefaultDaoImpl<>(dataSource, dbType, User.class);
List<User> userList = userDao.find(new User().setAge(21), "age");
System.out.println(userList);
}
@Test
public void count1() {
public void count1() throws SQLException {
Dao<User> userDao = new DefaultDaoImpl<>(dataSource, dbType, User.class);
System.out.println(userDao.count());
}
@Test
public void count2() {
public void count2() throws SQLException {
Dao<User> userDao = new DefaultDaoImpl<>(dataSource, dbType, User.class);
System.out.println(userDao.count(new User().setAge(21), "age"));
}
@@ -0,0 +1,38 @@
/**
* Copyright (C) 2018-2022 Zeyi information technology (Shanghai) Co., Ltd.
* <p>
* All right reserved.
* <p>
* This software is the confidential and proprietary
* information of Zeyi Company of China.
* ("Confidential Information"). You shall not disclose
* such Confidential Information and shall use it only
* in accordance with the terms of the contract agreement
* you entered into with Zeyi inc.
*/
package fun.asgc.neutrino.core.db.mapper;
import fun.asgc.neutrino.core.aop.interceptor.ExceptionHandler;
import lombok.extern.slf4j.Slf4j;
import java.sql.SQLException;
/**
*
* @author: aoshiguchen
* @date: 2022/6/30
*/
@Slf4j
public class TestExceptionHandler implements ExceptionHandler {
@Override
public boolean support(Exception e) {
return e instanceof SQLException;
}
@Override
public Object handle(Exception e) {
log.error("SQL执行异常", e);
return null;
}
}
@@ -22,6 +22,7 @@
package fun.asgc.neutrino.core.db.mapper;
import fun.asgc.neutrino.core.annotation.Component;
import fun.asgc.neutrino.core.aop.Intercept;
import fun.asgc.neutrino.core.db.annotation.Insert;
import fun.asgc.neutrino.core.db.annotation.ResultType;
import fun.asgc.neutrino.core.db.annotation.Select;
@@ -33,6 +34,7 @@ import java.util.List;
* @author: aoshiguchen
* @date: 2022/6/28
*/
@Intercept(exceptionHandler = TestExceptionHandler.class)
@Component
public interface UserMapper extends SqlMapper {
@@ -27,6 +27,7 @@ import lombok.Data;
import lombok.experimental.Accessors;
import org.junit.Test;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
@@ -49,12 +50,12 @@ public class JdbcTemplateTest {
}
@Test
public void 新增数据1() {
public void 新增数据1() throws SQLException {
jdbcTemplate.update("insert into user(`id`,`name`,`age`,`email`,`sex`,`create_time`) values(?,?,?,?,?,?)", 1, "张三", 21, "[email protected]", "", new Date());
}
@Test
public void 数据新增2() {
public void 数据新增2() throws SQLException {
Map<String, Object> params = new HashMap<>();
params.put("id", 2);
params.put("name", "李四");
@@ -66,7 +67,7 @@ public class JdbcTemplateTest {
}
@Test
public void 数据新增3() {
public void 数据新增3() throws SQLException {
User user = new User();
user.setId(3L);
user.setName("王五");
@@ -78,12 +79,12 @@ public class JdbcTemplateTest {
}
@Test
public void 更新数据1() {
public void 更新数据1() throws SQLException {
jdbcTemplate.update("update user set age = ? ,update_time = ? where id = ?", 31, new Date(), 1);
}
@Test
public void 更新数据2() {
public void 更新数据2() throws SQLException {
Map<String, Object> params = new HashMap<>();
params.put("id", 2);
params.put("updateTime", new Date());
@@ -92,7 +93,7 @@ public class JdbcTemplateTest {
}
@Test
public void 更新数据3() {
public void 更新数据3() throws SQLException {
User user = new User();
user.setId(3L);
user.setAge(33);
@@ -101,68 +102,68 @@ public class JdbcTemplateTest {
}
@Test
public void 删除数据1() {
public void 删除数据1() throws SQLException {
jdbcTemplate.update("delete from user where id = ?", 1L);
}
@Test
public void 删除数据2() {
public void 删除数据2() throws SQLException {
Map<String, Object> params = new HashMap<>();
params.put("id", 2);
jdbcTemplate.updateByMap("delete from user where id = :id", params);
}
@Test
public void 删除数据3() {
public void 删除数据3() throws SQLException {
User user = new User();
user.setId(3L);
jdbcTemplate.updateByModel("delete from user where id = :id", user);
}
@Test
public void 查询单个行记录1() {
public void 查询单个行记录1() throws SQLException {
Map<String, Object> map = jdbcTemplate.queryForMap("select * from user where id = ?", 1);
System.out.println(map);
}
@Test
public void 查询单个行记录2() {
public void 查询单个行记录2() throws SQLException {
User user = jdbcTemplate.query(User.class, "select * from user where id = 1");
System.out.println(user);
}
@Test
public void 查询单个字段记录1() {
public void 查询单个字段记录1() throws SQLException {
String name = jdbcTemplate.queryForString("select name from user where id = ?", 1);
System.out.println(name);
}
@Test
public void 查询单个字段记录2() {
public void 查询单个字段记录2() throws SQLException {
int age = jdbcTemplate.queryForInt("select age from user where id = 1");
System.out.println(age);
}
@Test
public void 查询单个字段记录3() {
public void 查询单个字段记录3() throws SQLException {
Long count = jdbcTemplate.queryForLong("select count(1) from user");
System.out.println(count);
}
@Test
public void 查询多个行记录1() {
public void 查询多个行记录1() throws SQLException {
List<Map> list = jdbcTemplate.queryForListMap("select * from user");
System.out.println(list);
}
@Test
public void 查询多个行记录2() {
public void 查询多个行记录2() throws SQLException {
List<User> list = jdbcTemplate.queryForList(User.class, "select * from user");
System.out.println(list);
}
@Test
public void 查询多个字段记录1() {
public void 查询多个字段记录1() throws SQLException {
List<Integer> list = jdbcTemplate.queryForListInt("select age from user");
System.out.println(list);
}