java项目中数据字典的实现

数据字典的使用

借助redis进行缓存来处理字典值替换。
依赖

<!--redis-->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
  <groupId>redis.clients</groupId>
  <artifactId>jedis</artifactId>
  <version>2.9.0</version>
</dependency>
<!--lombok-->
<dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
  <version>1.18.2</version>
  <optional>true</optional>
</dependency>

字典表:SYS_DICT

SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for SYS_DICT
-- ----------------------------
DROP TABLE IF EXISTS `SYS_DICT`;
CREATE TABLE `SYS_DICT` (
  `code` varchar(36) NOT NULL COMMENT '主键',
  `type_code` varchar(36) DEFAULT NULL COMMENT '类型code',
  `name` varchar(50) DEFAULT NULL COMMENT '展示值',
  `value` int(20) DEFAULT NULL COMMENT '使用值',
  `fixed` int(2) DEFAULT NULL COMMENT 'default 0不固定,固定的话用1',
  `creater` varchar(20) DEFAULT NULL COMMENT '新建人',
  `create_time` datetime DEFAULT NULL COMMENT '新建时间',
  `updater` varchar(20) DEFAULT NULL COMMENT '编辑人',
  `update_time` datetime DEFAULT NULL COMMENT '编辑时间',
  PRIMARY KEY (`code`),
  KEY `sys_type` (`type_code`),
  CONSTRAINT `sys_type` FOREIGN KEY (`type_code`) REFERENCES `SYS_DICT_TYPE` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


-- ----------------------------
-- Records of SYS_DICT
-- ----------------------------
INSERT INTO `SYS_DICT` VALUES ('182d4db6-aa50-11ea-aa1b-00163e08c9ed', '9ed92c7e-aa4f-11ea-aa1b-00163e08c9ed', '男', '0', '1', null, null, null, null);
INSERT INTO `SYS_DICT` VALUES ('222cf983-aa50-11ea-aa1b-00163e08c9ed', '9ed92c7e-aa4f-11ea-aa1b-00163e08c9ed', '女', '1', '1', null, null, null, null);

字典类型表SYS_DICT_TYPE:

SET FOREIGN_KEY_CHECKS=0;


-- ----------------------------
-- Table structure for SYS_DICT_TYPE
-- ----------------------------
DROP TABLE IF EXISTS `SYS_DICT_TYPE`;
CREATE TABLE `SYS_DICT_TYPE` (
  `code` varchar(36) NOT NULL,
  `name` varchar(50) DEFAULT NULL COMMENT '用于展示',
  `value` varchar(50) DEFAULT NULL COMMENT '用于前段(建立唯一索引)',
  `creater` varchar(20) DEFAULT NULL COMMENT '新建人',
  `create_time` datetime DEFAULT NULL COMMENT '新建时间',
  `updater` varchar(20) DEFAULT NULL COMMENT '编辑人',
  `updater_time` datetime DEFAULT NULL COMMENT '编辑时间',
  PRIMARY KEY (`code`),
  UNIQUE KEY `key_value` (`value`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


-- ----------------------------
-- Records of SYS_DICT_TYPE
-- ----------------------------
INSERT INTO `SYS_DICT_TYPE` VALUES ('9ed92c7e-aa4f-11ea-aa1b-00163e08c9ed', '性别', 'sex', null, null, null, null);

SpringUtil

/**
* 用于实现普通Pojo使用Service层
*/
@Component
public class SpringUtil implements ApplicationContextAware {


    private static ApplicationContext applicationContext = null;


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if(SpringUtil.applicationContext == null){
            SpringUtil.applicationContext  = applicationContext;
        }
    }

    //获取applicationContext
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }


    //通过name获取 Bean.
    public static Object getBean(String name){
        return getApplicationContext().getBean(name);
    }


    //通过class获取Bean.
    public static <T> T getBean(Class<T> clazz){
        return getApplicationContext().getBean(clazz);
    }

    //通过name,以及Clazz返回指定的Bean
    public static <T> T getBean(String name,Class<T> clazz){
        return getApplicationContext().getBean(name, clazz);
    }
}

RedisDistUtil

public class RedisDistUtil {
    private static ApplicationContext context;
    /**
     * 转化码值
     * @param distname
     * @param value
     * @return
     * @throws Exception
     */
    public static String transformStr(String distname, int value)  {
        ApplicationContext context = SpringUtil.getApplicationContext();
        ISysDictService iSysDictService =context.getBean(ISysDictService.class);
        return iSysDictService.transformStr(distname,value);
    }
}

SysDictService

@Transactional
@Service
public class SysDictService implements ISysDictService {

    @Autowired
    SysDictPojoMapper sysDictPojoMapper;


    @Autowired
    SysDictTypePojoMapper sysDictTypePojoMapper;


    @Autowired
    RedisTemplate redisTemplate;


    //日志记录器
    private static Logger logger = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);


    /**
     * 转化码值
     * @param distname
     * @param value
     * @return
     * @throws Exception
     */
    @Override
    public String transformStr(String distname, int value) {
        //查询redis
        String tmp = redisTemplate.opsForValue().get(distname+"_"+value).toString();
        if(StringUtils.isNotBlank(tmp)){
            return tmp;
        }
        //如果不存在,返回value
        //不直接查询数据库,是为了防止缓存穿透问题
        return String.valueOf(value);
    }
}

UserInfoPojo :在get方法里进行数据字典值的替换

/**
* 用户Pojo
*/
@Data
@TableName("tb_user")
@EqualsAndHashCode(callSuper = true)
@JsonIgnoreProperties(ignoreUnknown = true)
public class UserInfoPojo extends CommentPojo{


    private static final long serialVersionUID = 1L;
    //解决mybatis-plus和easyExcel的冲突问题
    @JsonIgnoreProperties(ignoreUnknown = true)
    @TableField(exist = false)
    private Map<Integer,CellStyle> cellStyleMap = new HashMap<Integer, CellStyle>();


    @TableId(type = IdType.UUID)
    private String id; //主键

    private Integer sex;//性别


    @ExcelProperty(value = "性别(必填)", index = 5)
    @TableField(exist = false)
    private String sexStr; //用于展示性别
    /**
     * 进行数字字典的替换
     * @return
     */
    public String getSexStr() {
        return RedisDistUtil.transformStr("sex",this.sex);
    }
}

验证结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_40990818/article/details/106669371