1 Star 0 Fork 217

dengyongbiao / easy_trans

forked from dromara / easy_trans 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

easy_trans

介绍

2021年啦,Mybatis Plus/Jpa的使用越来越多,项目中写SQL越来越少了,有的时候不得已还得写sql,比如: 关联字典,关联其他的表使用外键拿其他表的title/name 等等,为了更优雅的实现id变name/title 字典码变字典描述,easy trans横空出世,通过2个注解就能实现数据翻译,配合自己封装的一些baseService baseController,在配合一些代码生成器插件(比如EasyCode),可真正实现简单的CRUD不写一行代码的目标。

先看效果:
输入图片说明

easy trans适用于三种场景
1 我有一个id,但是我需要给客户展示他的title/name 但是我又不想做表关联查询
2 我有一个字典吗 sex 和 一个字典值0 我希望能翻译成 男 给客户展示。
3 我有一组user id 比如 1,2,3 我希望能展示成 张三,李四,王五 给客户

easy trans的三种模式
1 使用redis缓存模式
    一般用于分布式/微服务系统,比如我有用户服务和订单服务,在订单列表中需要展示创建人,他们又不是同一个进程,db也不是同一个,可使用redis 翻译模式

2 内存缓存(hashmap)模式
    一般用于单体模式,缓存放到hashmap中。

3 非缓存模式
    非缓存模式不使用缓存,调用 findbyids方法来获取数据用于翻译,一般用于表数据量比较大,缓存扛不住的情况。

安装教程

1 、先把maven 引用加上

       <dependency>
            <groupId>com.fhs-opensource</groupId>
            <artifactId>easy-trans-spring-boot-starter</artifactId>
            <version>1.0.1</version>
        </dependency>

2、如果使用Redis请添加redis的引用(如果之前加过了请不要重复添加)

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

3、在yaml中添加如下配置

easy-trans:
   autotrans:
       #您的service所在的包 支持通配符比如com.*.**.service.**,他的默认值是com.*.*.service.impl
       package: com.fhs.test.service.** 
	   #启用redis缓存
   is-enable-redis: true
  #yixi 
spring:
  redis:
    host: 192.168.0.213
    port: 6379
    password: 123456
    database: 0
    timeout: 6000

4、如果不使用redis,请在启动类加禁用掉redis的自动配置类

@SpringBootApplication(exclude = { RedisAutoConfiguration.class })

使用说明(请务必看完本段)

1、字典翻译使用说明---直接上代码了,可以配合InitializingBean一起玩.
  1.1 翻译缓存初始化

    @Autowired  //注入字典翻译服务
    private  DictionaryTransService dictionaryTransService;
	
	   //在某处将字典缓存刷新到翻译服务中,以下是demo
	    Map<String,String> transMap = new HashMap<>();
        transMap.put("0","男");
        transMap.put("1","女");
        dictionaryTransService.refreshCache("sex",transMap);

  1.2 字典翻译使用

   //在对应的字段上 加此注解,type为TransType.DICTIONARY,key为字典分组码,ref为选填,如果设置了则会自动将翻译结果设置到此字段上
     @Trans(type = TransType.DICTIONARY,key = "sex",ref = "sexName")
    private Integer sex;

    private String sexName;

2、AutoTrans(除了字典外的其他表翻译)使用说明---直接上代码了,可以配合InitializingBean一起玩.
  2.1 service实现类改动,主要2个点1是添加AutoTrans注解,2 是实现AutoTransAble 接口

@Service
@AutoTrans(namespace = "teacher",fields = "name",defaultAlias = "teacher",useCache = true,useRedis = true)  //namespace = 表别名  fields = 哪些字段需要出现在翻译结果中这里写了name defaultAlias =默认别名,比如我这里有个name字段别的表也有个name字段,为了区分这里配置为teacher 在翻译结果中 就会出现teacherName 而不是name  useCache = 是否使用缓存  useRedis = 是否使用redis缓存
public class TeacherService implements AutoTransAble {

   //在不使用缓存的时候使用,如果transMore的时候会拼接teacherid集合,调用此方法获取id集合对应的teacher对象
     public List<P> findByIds(List<?> ids) {
	    //推荐使用JPA/Mybatis Plus的方法哦
        return this.baseMapper.selectBatchIds(ids);
    }
 
 // 在开启缓存的时候,springboot启动完成后会拿所有数据放到缓存里
    @Override
    public List select() {
      return  this.baseMapper.selectList((Wrapper)null)
    }

// 在不开启缓存的时候,transone会通过此方法获取翻译数据
    @Override
    public VO selectById(Object primaryValue) {
       return this.baseMapper.selectById(primaryValue);
    }

以上,建议在baseservice中添加以上几个方法,这样子service就不用每个都写了。

  2.2 Autotrans翻译使用

     //指定翻译的namespace,和翻译类型为TransType.AUTO_TRANS
    @Trans(type = TransType.AUTO_TRANS,key = "teacher")
    private String teacherId;
   //如果有2个teacherid 可以通过namespace#别名  来起别名区分
    @Trans(type = TransType.AUTO_TRANS,key = "teacher#english")
    private String englishteacherId;

    //同样支持ref ,将字翻译结果赋值到某个字段上
    @Trans(type = TransType.AUTO_TRANS,key = "teacher",ref = "teacherName")
    private String teacherId;

    private String teacherName;

    //如果teacher 对外开放了多个字段当做翻译结果,比如 name和age,我这里只要age  ref可以同如下写法
    @Trans(type = TransType.AUTO_TRANS,key = "teacher#english",ref = "engTeacherAge#age")
    private String englishteacherId;

    private String engTeacherAge;

3、POJO修改 a 实现vo接口(Teacher类也要实现哦),提供一个transMap,框架会把翻译结果put到这个map中,建议使用basePOJO 的方法来实现

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Student implements VO {

    private String studentName;

    @Trans(type = TransType.AUTO_TRANS,key = "teacher")
    private String teacherId;

    @Trans(type = TransType.AUTO_TRANS,key = "teacher#english")
    private String englishteacherId;

    @Trans(type = TransType.DICTIONARY,key = "sex")
    private Integer sex;

    public Map<String,String> transMap = new HashMap<>();

    @Override
    public Map<String, String> getTransMap() {
        return transMap;
    }
}

4、框架中没有使用JPA/Mybatis Plus怎么办

   //vo中有一个getPkey 方法默认是找@Id 或者 @TableId 标识的字段,如果没有使用JPA/Mybatis Plus 可重写此方法返回表主键的值比如 return this.id;

    @JsonIgnore
    @JSONField(serialize = false)
     default Object getPkey(){
         Field idField = getIdField(true);
         try {
             return idField.get(this);
         } catch (IllegalAccessException e) {
             return null;
         }
     }

5、准备工作已经完成,最后一步,使用翻译服务进行翻译

    @Autowired
    private TransService transService;

    @Test
    public void transOne(){
        Student student = new Student();
        student.setStudentName("张三");
        student.setTeacherId("1");
        student.setEnglishteacherId("2");
        student.setSex(1);
		//翻译一个对象
        transService.transOne(student);
        System.out.println(JsonUtils.bean2json(student));
    }


    @Test
    public void transMore(){
        Student student = new Student();
        student.setStudentName("张三");
        student.setTeacherId("1");
        student.setEnglishteacherId("2");
        student.setSex(1);
        List<Student> studentList = new ArrayList<>();
        studentList.add(student);
		//翻译多个对象
        transService.transMore(studentList);
        System.out.println(JsonUtils.list2json(studentList));
    }

6、缓存刷新
  6.1 非集群模式下的缓存刷新
调用AutoTransService的refreshCache(Map<String, Object> messageMap)
map中put一个namespace 为teacher的话,就代表刷新teacher的缓存,如果map中什么都不put代表刷新所有缓存。
  6.2 集群模式下的缓存刷新(必须开启redis支持才可以)

 @Autowired
 private RedisCacheService redisCacheService;
 Map<String, String> message = new HashMap();
            message.put("transType", "auto");
            message.put("namespace", "teacher");
            this.redisCacheService.convertAndSend("trans", JsonUtils.map2json(message));

7、DEMO https://gitee.com/fhs-opensource/easy_trans_springboot_demo

参与贡献

  1. 如果遇到使用问题可以加QQ群:976278956

写到最后

教程看起来挺麻烦,只需要做2处封装,使用起来就很简单了,第一就是baseserivce的封装(主要提供那三个获取翻译数据的方法 和 缓存刷新的方法),第二就是base pojo的封装(主要是getTransMap 给翻译服务返回一个hashmap用来装填数据用),作者已经和ruoyi guns 做好了对接,需要资料什么的可以直接加群联系作者。

Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed 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.

简介

easy trans适用于两种场景 1 我有一个id,但是我需要给客户展示他的title/name 但是我又不想做表关联查询 2 我有一个字典吗 sex 和 一个字典值0 我希望能翻译成 男 给客户展示。 展开 收起
Java
Apache-2.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
Java
1
https://gitee.com/simonmis/easy_trans.git
git@gitee.com:simonmis/easy_trans.git
simonmis
easy_trans
easy_trans
master

搜索帮助