SqlMapper相关功能优化、完善

This commit is contained in:
aoshiguchen
2022-06-29 18:02:36 +08:00
parent d7ebb55756
commit fec58c39ef
5 changed files with 161 additions and 13 deletions
@@ -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<Method, Params> 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;
}
}
@@ -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;
}
});
}
}
@@ -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<User> 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("[email protected]");
user2.setSex("");
user2.setCreateTime(new Date());
System.out.println(userMapper.add(user2));
}
}
@@ -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<User> 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);
}
@@ -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<Map> list = jdbcTemplate.queryForListMap("select * from user");