前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >spring获取AliasFor增强的注解

spring获取AliasFor增强的注解

作者头像
阿超
发布于 2023-06-23 06:24:44
发布于 2023-06-23 06:24:44
22700
代码可运行
举报
文章被收录于专栏:快乐阿超快乐阿超
运行总次数:0
代码可运行

无论何时,别让你自己卷进去反对他人。——歌德

此处是关于issuehttps://gitee.com/dromara/stream-query/issues/I7BSNV

这里使用的一个自定义的@Table注解+@AliasFor来增强@TableName

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package issue.org.dromara.streamquery.gitee.issue17BSNV;

import com.baomidou.mybatisplus.annotation.TableName;
import org.springframework.core.annotation.AliasFor;

import java.lang.annotation.*;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@TableName
public @interface Table {
  @AliasFor(annotation = TableName.class, attribute = "value")
  String value() default "";
}

然后是

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package issue.org.dromara.streamquery.gitee.issue17BSNV;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import lombok.Data;
import org.dromara.streamquery.stream.plugin.mybatisplus.engine.mapper.IGenerateMapper;

import java.time.LocalDateTime;

@Data
@Table(value = "user_info")
public class UserInfoWithTableAnnotation implements IGenerateMapper {
  private static final long serialVersionUID = -7219188882388819210L;

  @TableId(value = "id", type = IdType.AUTO)
  private Long id;

  private String name;
  private Integer age;
  private String email;

  @TableLogic(value = "'2001-01-01 00:00:00'", delval = "NOW()")
  private LocalDateTime gmtDeleted;
}

使用时:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package issue.org.dromara.streamquery.gitee.issue17BSNV;

import org.dromara.streamquery.stream.core.collection.Lists;
import org.dromara.streamquery.stream.plugin.mybatisplus.Database;
import org.dromara.streamquery.stream.plugin.mybatisplus.annotation.AbstractMybatisPlusTestApplication;
import org.dromara.streamquery.stream.plugin.mybatisplus.engine.annotation.EnableMybatisPlusPlugin;
import org.dromara.streamquery.stream.plugin.mybatisplus.engine.mapper.IMapper;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;

import java.util.Arrays;
import java.util.List;

/**
 * @author VampireAchao
 * @since 2023/6/8
 */
@EnableAutoConfiguration
@EnableMybatisPlusPlugin
class RevisionTest extends AbstractMybatisPlusTestApplication {

  @Test
  void testExecute() {
    UserInfoWithTableAnnotation entity = new UserInfoWithTableAnnotation();
    entity.setName("cat");
    entity.setAge(20);
    entity.setEmail("myEmail");
    UserInfoWithTableAnnotation userInfo = new UserInfoWithTableAnnotation();
    userInfo.setName("ruben");
    List<UserInfoWithTableAnnotation> list = Arrays.asList(userInfo, entity);
    long effectRows = Database.execute(UserInfoWithTableAnnotation.class,
            (IMapper<UserInfoWithTableAnnotation> m) -> m.saveOneSql(list));
    Assertions.assertEquals(2, effectRows);
    Assertions.assertEquals(7, Database.count(UserInfoWithTableAnnotation.class));

    Assertions.assertEquals(
            0L, Database.execute(UserInfoWithTableAnnotation.class,
                    (IMapper<UserInfoWithTableAnnotation> m) -> m.saveOneSql(Lists.empty())));
  }
}

此时发现并没有映射上,这里找表名没有找到。。。

于是我进行了处理

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
String originalTableName = tableInfo.getTableName();
  Annotation[] annotations = tableInfo.getEntityType().getAnnotations();
  for (Annotation annotation : annotations) {
    if (annotation.annotationType().isAnnotationPresent(TableName.class)) {
      Map<String, Object> annotationAttributes =
          AnnotationUtils.getAnnotationAttributes(annotation);
      TableName synthesizedTableName =
          AnnotationUtils.synthesizeAnnotation(
              annotationAttributes, TableName.class, tableInfo.getEntityType());
      String tableNamePropertyName = LambdaHelper.getPropertyName(TableInfo::getTableName);
      String tableNameValue = synthesizedTableName.value();
      ReflectHelper.setFieldValue(tableInfo, tableNamePropertyName, tableNameValue);
      Map<String, TableInfo> tableNameInfoCache =
          ((SerSupp<Map<String, TableInfo>>)
                  () ->
                      SerFunc.<Object, Map<String, TableInfo>>cast()
                          .apply(
                              ReflectHelper.accessible(
                                      TableInfoHelper.class.getDeclaredField(
                                          "TABLE_NAME_INFO_CACHE"))
                                  .get(null)))
              .get();
      tableNameInfoCache.remove(originalTableName);
      tableNameInfoCache.put(tableNameValue, tableInfo);
      break;
    }

完整代码如下:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.dromara.streamquery.stream.plugin.mybatisplus.engine.handler;

import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.core.handlers.PostInitTableInfoHandler;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import org.apache.ibatis.mapping.ResultMap;
import org.apache.ibatis.mapping.ResultMapping;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.TypeHandler;
import org.dromara.streamquery.stream.core.lambda.LambdaHelper;
import org.dromara.streamquery.stream.core.lambda.function.SerFunc;
import org.dromara.streamquery.stream.core.lambda.function.SerSupp;
import org.dromara.streamquery.stream.core.reflect.ReflectHelper;
import org.springframework.core.annotation.AnnotationUtils;

import java.lang.annotation.Annotation;
import java.util.Map;

/**
 * @author VampireAchao
 * @since 2023/3/20 18:10
 */
public class JsonPostInitTableInfoHandler implements PostInitTableInfoHandler {

  /**
   * 参与 TableInfo 初始化
   *
   * @param tableInfo TableInfo
   * @param configuration Configuration
   */
  @Override
  public void postTableInfo(TableInfo tableInfo, Configuration configuration) {
    PostInitTableInfoHandler.super.postTableInfo(tableInfo, configuration);
    String originalTableName = tableInfo.getTableName();
    Annotation[] annotations = tableInfo.getEntityType().getAnnotations();
    for (Annotation annotation : annotations) {
      if (annotation.annotationType().isAnnotationPresent(TableName.class)) {
        Map<String, Object> annotationAttributes =
            AnnotationUtils.getAnnotationAttributes(annotation);
        TableName synthesizedTableName =
            AnnotationUtils.synthesizeAnnotation(
                annotationAttributes, TableName.class, tableInfo.getEntityType());
        String tableNamePropertyName = LambdaHelper.getPropertyName(TableInfo::getTableName);
        String tableNameValue = synthesizedTableName.value();
        ReflectHelper.setFieldValue(tableInfo, tableNamePropertyName, tableNameValue);
        Map<String, TableInfo> tableNameInfoCache =
            ((SerSupp<Map<String, TableInfo>>)
                    () ->
                        SerFunc.<Object, Map<String, TableInfo>>cast()
                            .apply(
                                ReflectHelper.accessible(
                                        TableInfoHelper.class.getDeclaredField(
                                            "TABLE_NAME_INFO_CACHE"))
                                    .get(null)))
                .get();
        tableNameInfoCache.remove(originalTableName);
        tableNameInfoCache.put(tableNameValue, tableInfo);
        break;
      }
    }

    for (TableFieldInfo fieldInfo : tableInfo.getFieldList()) {
      if (fieldInfo.getTypeHandler() == null) {
        continue;
      }
      if (tableInfo.getResultMap() == null) {
        return;
      }
      ResultMap resultMap = configuration.getResultMap(tableInfo.getResultMap());
      for (ResultMapping resultMapping : resultMap.getResultMappings()) {
        TypeHandler<?> handler = resultMapping.getTypeHandler();
        if (handler instanceof AbstractJsonFieldHandler) {
          AbstractJsonFieldHandler<?> typeHandler = (AbstractJsonFieldHandler<?>) handler;
          typeHandler.setTableInfo(tableInfo);
          typeHandler.setFieldInfo(fieldInfo);
        }
      }
    }
  }
}

然后通过AnnotationUtils.*synthesizeAnnotation*解决了这个问题

完整代码:

https://gitee.com/dromara/stream-query/commit/f4c15fdca66c5e6037644b0888e2b756eb5db25a

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2023-06-14,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
mp方法注入支持typeHandler
#{et.name,typeHandler=org.dromara.streamquery.stream.plugin.mybatisplus.JsonFieldHandlerTest$JsonFieldHandler} 即可直接指定typeHandler
阿超
2023/06/23
2520
spring-gateway跨域坑
阿超
2023/12/30
1980
stream-query的BeanHelper拷贝支持Converter
这里可以自定义Converter,此处new CopyOption()是不带默认内置的Converter的,但是CopyOption.of()是带的
阿超
2024/01/23
1420
java:axis2环境下获取方法参数名的另一种方法
想获取”param1”,和”param2”这个参数名,肯定是不行的。关于获取方法的参数名字(不是参数类型),一般的做法是借助第三方包javassist或asm来实现。参见下面的文章:
10km
2022/05/07
2230
h2下update set字段重复处理拦截器
今天发现Mybatis-Plus在h2下,同时使用UpdateWrapper和entity会出现
阿超
2022/09/28
4890
MyBatis-Plus之注解
我们现在指定数据库表和mappr的关联在是在mapper接口中引入的user进行的绑定;
默 语
2024/11/20
510
MyBatis-Plus之注解
mybatis-plus默认查询方式
则可以在对应属性上加上注解@TableField并指定condition = SqlCondition.LIKE,就像这样
阿超
2022/08/16
1K0
mybatis-plus默认查询方式
升级mp新版本后,service里removeByIds主键类型不一致报错
主键类型是Integer,使用service中removeByIds,传入List<String>报错
阿超
2023/01/07
6150
mybatis的@MappedTypes
看到com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler的源码
阿超
2024/03/19
4170
stream-query开源合规
然后使用license-eye,我是用brew install license-eye
阿超
2024/03/29
1560
【Spring Boot】012-Shiro入门
Shiro是一个强大且易于使用的 Java 安全框架,它执行身份验证、授权、加密和会话管理。有了 Shiro 的易于理解的 API,你可以快速而轻松地保护任何应用程序——从最小的移动应用程序到最大的 web 和企业应用程序;
訾博ZiBo
2025/01/06
920
【Spring Boot】012-Shiro入门
Spring Cloud Alibaba(四):Nacos服务注册与发现
微服务的起点就是服务注册与发现,Spring Cloud Alibaba系列将使用Nacos作为服务注册与发现。
冯文议
2021/04/28
5250
Spring Cloud Alibaba(四):Nacos服务注册与发现
Flink 自定义SQL实现Hudi MOR表压缩
Hudi在构建流式数据湖方面具有领先地位。Flink作为真正的流处理引擎,与Hudi搭配是理所应当的事情了。但是目前Hudi MOR表压缩功能除了在线压缩以外,并不能通过SQL实现手动压缩。目前的实现方式为:
从大数据到人工智能
2022/09/16
8310
Flink 自定义SQL实现Hudi MOR表压缩
开发dubbo应用程序(一)入门demo详解
https://github.com/apache/dubbo-samples/tree/2.6.x
Dream城堡
2019/08/07
1.1K0
开发dubbo应用程序(一)入门demo详解
dubbo SpringContainer
如果直接使用SpringContainer 则需要把相应的配置文件放到相应的位置,SpringContainer使用common log,
WindWant
2020/09/11
4710
动态mapper优先级问题
https://gitee.com/VampireAchao/stream-query/issues/I6EJ27
阿超
2023/03/19
3860
struts标签 checkboxlist 换行解决办法
struts标签 checkboxlist 默认是不换行的,显示列表会非常丑,百度了一圈解决办法就是要修改源文件
西门呀在吹雪
2020/11/09
6440
struts标签 checkboxlist 换行解决办法
mp中typeHandler自动获取字段类型
相熟的人表现出恭而敬之的样子总是叫人感到可笑。——歌德 一般我们在实体类上指定 @TableName(autoResultMap = true) 即可使用typeHandler指定转换器,然后就可以自动转换了 例如List<XXX>的Json可以如下使用: @TableField(typeHandler = JsonListHandler.class) private List<CalcUnitEnum> calcUnits; 这里JsonListHandler如下,JacksonUtil就懒得赘述了:
阿超
2023/03/23
1.3K0
webflux之webclient踩坑tablefield
发现调用一直抛出java.lang.NoClassDefFoundError说是mybatis的org.apache.ibatis.type.JdbcType找不到…
阿超
2024/02/10
1360
apache-streamparkpr和代码规范指南
https://github.com/apache/incubator-streampark-website/pull/226
阿超
2023/09/02
2890
相关推荐
mp方法注入支持typeHandler
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档