From fec58c39efb791b9f1bddf775f3d30debeca398d Mon Sep 17 00:00:00 2001 From: aoshiguchen <1052045476@qq.com> Date: Wed, 29 Jun 2022 18:02:36 +0800 Subject: [PATCH] =?UTF-8?q?SqlMapper=E7=9B=B8=E5=85=B3=E5=8A=9F=E8=83=BD?= =?UTF-8?q?=E4=BC=98=E5=8C=96=E3=80=81=E5=AE=8C=E5=96=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../core/db/mapper/SqlMapperInterceptor.java | 118 ++++++++++++++++-- .../type/extension/NumberMatcherGroup.java | 12 ++ .../asgc/neutrino/core/db/mapper/Test1.java | 18 ++- .../neutrino/core/db/mapper/UserMapper.java | 14 +++ .../core/db/template/JdbcTemplateTest.java | 12 ++ 5 files changed, 161 insertions(+), 13 deletions(-) diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/mapper/SqlMapperInterceptor.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/mapper/SqlMapperInterceptor.java index 0167cfd7..f1253624 100644 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/mapper/SqlMapperInterceptor.java +++ b/neutrino-core/src/main/java/fun/asgc/neutrino/core/db/mapper/SqlMapperInterceptor.java @@ -25,12 +25,17 @@ import fun.asgc.neutrino.core.annotation.Autowired; import fun.asgc.neutrino.core.annotation.Component; import fun.asgc.neutrino.core.aop.Invocation; import fun.asgc.neutrino.core.aop.interceptor.Interceptor; -import fun.asgc.neutrino.core.db.annotation.Select; +import fun.asgc.neutrino.core.cache.Cache; +import fun.asgc.neutrino.core.cache.MemoryCache; +import fun.asgc.neutrino.core.db.annotation.*; import fun.asgc.neutrino.core.db.template.JdbcTemplate; -import fun.asgc.neutrino.core.util.Assert; -import fun.asgc.neutrino.core.util.StringUtil; +import fun.asgc.neutrino.core.util.*; +import lombok.Data; +import lombok.experimental.Accessors; +import java.lang.reflect.Method; import java.util.Collection; +import java.util.Map; /** * sqlmapper拦截器 @@ -42,21 +47,110 @@ public class SqlMapperInterceptor implements Interceptor { @Autowired private JdbcTemplate jdbcTemplate; + private static final Cache paramsCache = new MemoryCache<>(); @Override public void intercept(Invocation inv) { Assert.notNull(jdbcTemplate, "JdbcTemplate未注入,调用失败!"); - if (inv.getTargetMethod().isAnnotationPresent(Select.class)) { - Select select = inv.getTargetMethod().getAnnotation(Select.class); - String sql = select.value(); - if (StringUtil.isEmpty(sql)) { - throw new RuntimeException("sql不能为空!"); + Params params = getParams(inv.getTargetMethod()); + if (null == params) { + return; + } + String sql = params.getSql(); + Class resultType = params.getResultType(); + Object res = null; + if (params.isSelect()) { + if (params.isReturnCollection()) { + res = jdbcTemplate.queryForList(resultType, sql, inv.getArgs()); + } else { + res = jdbcTemplate.query(resultType, sql, inv.getArgs()); } - Class returnType = inv.getReturnType(); - if (!Collection.class.isAssignableFrom(returnType)) { - Object res = jdbcTemplate.query(returnType, sql, inv.getArgs()); - inv.setReturnValue(res); + } else if (params.isInsert() || params.isDelete() || params.isUpdate()) { + int argsCount = ArrayUtil.isEmpty(inv.getArgs()) ? 0 : inv.getArgs().length; + if (argsCount == 1 && inv.getArgs()[0] instanceof Map) { + res = jdbcTemplate.updateByMap(sql, (Map)inv.getArgs()[0]); + } else if (argsCount == 1 && !TypeUtil.isNormalBasicType(inv.getArgs()[0].getClass())) { + res = jdbcTemplate.updateByModel(sql, inv.getArgs()[0]); + } else { + res = jdbcTemplate.update(sql, inv.getArgs()); } } + inv.setReturnValue(TypeUtil.conversion(res, resultType)); + } + + /** + * 获取参数 + * @param method + * @return + */ + private static Params getParams(Method method) { + return LockUtil.doubleCheckProcess( + () -> !paramsCache.containsKey(method), + method, + () -> { + String sign = String.format("%s#%s", method.getDeclaringClass().getName(), method.getName()); + Params params = null; + ResultType resultType = method.getAnnotation(ResultType.class); + Class resultClass = (null == resultType) ? null : resultType.value(); + + if (method.isAnnotationPresent(Select.class)) { + // 查询 + Select select = method.getAnnotation(Select.class); + String sql = select.value(); + if (StringUtil.isEmpty(sql)) { + throw new RuntimeException(String.format("%s sql不能为空!", sign)); + } + boolean isReturnCollection = Collection.class.isAssignableFrom(method.getReturnType()); + if (isReturnCollection && null == resultClass) { + throw new RuntimeException(String.format("%s 请指名实体类型!", sign)); + } + params = new Params().setSql(sql).setSelect(true).setResultType(resultClass).setReturnCollection(isReturnCollection); + } else if (method.isAnnotationPresent(Insert.class)) { + // 新增 + Insert insert = method.getAnnotation(Insert.class); + String sql = insert.value(); + if (StringUtil.isEmpty(sql)) { + throw new RuntimeException(String.format("%s sql不能为空!", sign)); + } + params = new Params().setSql(sql).setInsert(true).setResultType(resultClass); + } else if (method.isAnnotationPresent(Delete.class)) { + // 删除 + Delete delete = method.getAnnotation(Delete.class); + String sql = delete.value(); + if (StringUtil.isEmpty(sql)) { + throw new RuntimeException(String.format("%s sql不能为空!", sign)); + } + params = new Params().setSql(sql).setDelete(true).setResultType(resultClass); + } else if (method.isAnnotationPresent(Update.class)) { + // 更新 + Update update = method.getAnnotation(Update.class); + String sql = update.value(); + if (StringUtil.isEmpty(sql)) { + throw new RuntimeException(String.format("%s sql不能为空!", sign)); + } + params = new Params().setSql(sql).setUpdate(true).setResultType(resultClass); + } + if (null == params) { + throw new RuntimeException(String.format("%s 缺失SQL注解!", sign)); + } + if (null == params.getResultType() && !Collection.class.isAssignableFrom(method.getReturnType())) { + params.setResultType(method.getReturnType()); + } + paramsCache.set(method, params); + }, + () -> paramsCache.get(method) + ); + } + + @Accessors(chain = true) + @Data + static class Params { + private String sql; + private Class resultType; + private boolean isReturnCollection; + private boolean isSelect; + private boolean isDelete; + private boolean isUpdate; + private boolean isInsert; } } diff --git a/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/extension/NumberMatcherGroup.java b/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/extension/NumberMatcherGroup.java index 43ce104c..44501613 100644 --- a/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/extension/NumberMatcherGroup.java +++ b/neutrino-core/src/main/java/fun/asgc/neutrino/core/type/extension/NumberMatcherGroup.java @@ -164,6 +164,18 @@ public class NumberMatcherGroup extends AbstractExtensionMatcherGroup { return matchInfo; } }); + // Long - > int + add(new TypeMatcher() { + @Override + public TypeMatchInfo match(Class clazz, Class targetClass) { + TypeMatchInfo matchInfo = new TypeMatchInfo(clazz, targetClass, this); + if (TypeUtil.isInteger(targetClass) && TypeUtil.isLong(clazz)) { + matchInfo.setTypeDistance(getDistanceMin() + 7); + matchInfo.setTypeConverter(((value, targetType) -> ((Long)value).intValue())); + } + return matchInfo; + } + }); } } diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/mapper/Test1.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/mapper/Test1.java index 9886cb33..d986f5ff 100644 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/mapper/Test1.java +++ b/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/mapper/Test1.java @@ -15,9 +15,13 @@ package fun.asgc.neutrino.core.db.mapper; import com.alibaba.fastjson.JSONObject; import fun.asgc.neutrino.core.annotation.Autowired; import fun.asgc.neutrino.core.annotation.Component; +import fun.asgc.neutrino.core.db.template.JdbcTemplateTest; import fun.asgc.neutrino.core.runner.ApplicationRunner; import lombok.extern.slf4j.Slf4j; +import java.util.Date; +import java.util.List; + /** * * @author: aoshiguchen @@ -32,6 +36,18 @@ public class Test1 implements ApplicationRunner { @Override public void run(String[] args) { User user = userMapper.findOneById(1L); - log.info("查询结果:{}", JSONObject.toJSONString(user)); + log.info("查询结果1:{}", JSONObject.toJSONString(user)); + List userList = userMapper.findAll(); + log.info("查询结果2:{}", JSONObject.toJSONString(userList)); + log.info("查询结果3:{}", userMapper.count()); + + User user2 = new User(); + user2.setId(6L); + user2.setName("李八"); + user2.setAge(24); + user2.setEmail("liba@qq.com"); + user2.setSex("男"); + user2.setCreateTime(new Date()); + System.out.println(userMapper.add(user2)); } } diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/mapper/UserMapper.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/mapper/UserMapper.java index e651dccb..b1d59c54 100644 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/mapper/UserMapper.java +++ b/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/mapper/UserMapper.java @@ -22,8 +22,12 @@ package fun.asgc.neutrino.core.db.mapper; import fun.asgc.neutrino.core.annotation.Component; +import fun.asgc.neutrino.core.db.annotation.Insert; +import fun.asgc.neutrino.core.db.annotation.ResultType; import fun.asgc.neutrino.core.db.annotation.Select; +import java.util.List; + /** * * @author: aoshiguchen @@ -34,4 +38,14 @@ public interface UserMapper extends SqlMapper { @Select("select * from user where id = ?") User findOneById(Long id); + + @ResultType(User.class) + @Select("select * from user") + List findAll(); + + @Select("select count(1) from user") + int count(); + + @Insert("insert into user(`id`,`name`,`age`,`email`,`sex`,`create_time`) values(:id,:name,:age,:email,:sex,:createTime)") + int add(User user); } diff --git a/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/template/JdbcTemplateTest.java b/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/template/JdbcTemplateTest.java index 143bee96..3a0d9814 100644 --- a/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/template/JdbcTemplateTest.java +++ b/neutrino-core/src/test/java/fun/asgc/neutrino/core/db/template/JdbcTemplateTest.java @@ -137,6 +137,18 @@ public class JdbcTemplateTest { System.out.println(name); } + @Test + public void 查询单个字段记录2() { + int age = jdbcTemplate.queryForInt("select age from user where id = 1"); + System.out.println(age); + } + + @Test + public void 查询单个字段记录3() { + Long count = jdbcTemplate.queryForLong("select count(1) from user"); + System.out.println(count); + } + @Test public void 查询多个行记录1() { List list = jdbcTemplate.queryForListMap("select * from user");