目录
字典转换简介
以前我们从数据字典里面取值,拿到的都是一堆状态码,我们需要在前台进行判断,然后转义成中文,这样是十分麻烦的,这又是每个字典字段不可少的一个地方,所以我就想到了利用切面来帮我们实现中文的转义。
首先直接看下最后实现的效果吧,一般我们的数据字典接口就之后返回我们的状态码,在aop处理过之后,它把我们的一些爱好、成绩等状态码转成了中文多加了几个字段一并返回给我们,这样我们在前台绑定的时候就能直接通过_text的字段进行绑定了,不需要进行转义了
实现思路:用aop拦截我们的字典查询方法,我们遍历查询出的code,然后通过code去调用方法查询出它对应的text文本值,添加了注解@Dict(dicDataSource = “stu_sex”) 会在字典服务立马查出来对应的text 然后在请求list的时候将这个字典text,已字段名称加_dictText形式返回到前端(例如:我的学生等级字段是stulevel,然后我们通过拿到这个字段的值2去查询出它对应的等级B,然后把这个字段赋值给我们的stulevel_dictText然后一并添加到方法中返回),然后前端就可以直接取这个字段进行赋值
案例所用表
首先我们需要先自定义一个注解,这个注解主要是用来标识我们哪些字段是需要转义的
package com.xy.elasticsearch.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Dict {
/**
* 方法描述: 数据dataSource
* @return 返回类型: String
*/
String dicDataSource();
/**
* 方法描述: 这是返回后Put到josn中的文本 key 值
* @return 返回类型: String
*/
String dicText() default "";
}
主要的两个方法,一个是查询出我们所有的字典数据,一个是通过code取查询text值
<!-- 查询出所有学生数据 -->
<select id="listPager" resultType="com.xy.elasticsearch.entity.Student" parameterType="com.xy.elasticsearch.entity.Student">
select
<include refid="Base_Column_List" />
from t_annotation_student
<where>
<if test="name != null and name != ''">
and name like concat(concat('%',#{
name}),'%')
</if>
</where>
</select>
<!--根据code去查询text文本-->
<select id="queryByDatasourceCode" parameterType="com.xy.elasticsearch.entity.DataItem" resultType="com.xy.elasticsearch.entity.DataItem">
select
<include refid="Base_Column_List"></include>
from t_annotation
<where>
<if test="datasource != null and datasource != ''">
and datasource = #{
datasource}
</if>
<if test="code != null and code != ''">
and code = #{
code}
</if>
</where>
</select>
service层
package com.xy.elasticsearch.service;
import com.xy.elasticsearch.entity.DataItem;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import javax.xml.crypto.Data;
/**
* @author 阳某
* @create 2020-03-22 13:44
*/
@Repository
public interface DataItemService {
DataItem queryByDatasourceCode(DataItem dataItem);
String queryBydatasourceKey(String datasource, String key);
}
方法实现
package com.xy.elasticsearch.service.impl;
import com.xy.elasticsearch.entity.DataItem;
import com.xy.elasticsearch.entity.DataItemMapper;
import com.xy.elasticsearch.service.DataItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.xml.crypto.Data;
/**
* @author 阳某
* @create 2020-03-22 14:23
*/
@Service
public class DataItemServiceImpl implements DataItemService {
@Autowired
private DataItemMapper dataItemMapper;
@Override
public DataItem queryByDatasourceCode(DataItem dataItem) {