数据字典在项目中是不可缺少的“基础设施”,关于数据字典如何设计如何实现,今天抽空讲一下吧
先看一下表设计:
通过自定义标签来实现页面的渲染:
public class DataDictValueTag extends SimpleTagSupport { private String typeCode; private String ddKey; StringWriter sw = new StringWriter(); public void doTag() throws JspException, IOException {
if (StringUtils.isNotEmpty(typeCode) && StringUtils.isNotEmpty(ddKey)) { DataDictService ddService = (DataDictService)SpringContextUtil.getBean(DataDictService.class);
String ddValue = ddService.queryDataDictValueByCodeKey(typeCode, ddKey); JspWriter out = getJspContext().getOut();
out.println(ddValue);
} else {
getJspBody().invoke(sw);
getJspContext().getOut().println(sw.toString());
}
} public String getTypeCode() {
return typeCode;
} public void setTypeCode(String typeCode) {
this.typeCode = typeCode;
} public String getDdKey() {
return ddKey;
} public void setDdKey(String ddKey) {
this.ddKey = ddKey;
} }
再看一下service,根据字典码和数据字典key来获取具体的值:
需要注意的是数据字典属于静态数据,要放到redis中
@Override
public String queryDataDictValueByCodeKey(String typeCode, String ddKey) {
String redisKey = "redis_datadict:" + typeCode + ":" + ddKey;
// 从缓存中获取数据字典的值,如果没有该值,则从数据库中获取,最后再存入redis中
String redisDdvalue = jedis.get(redisKey);
if (StringUtils.isNotEmpty(redisDdvalue)) {
return redisDdvalue;
} DataDictExample dataDictExample = new DataDictExample();
Criteria dataDictCriteria = dataDictExample.createCriteria();
dataDictCriteria.andTypeCodeEqualTo(typeCode);
dataDictCriteria.andDdkeyEqualTo(ddKey);
dataDictCriteria.andIsShowEqualTo(YesOrNo.YES.value);
List<DataDict> list = dataDictMapper.selectByExample(dataDictExample);
if (list != null && list.size() > 0) {
DataDict dd = (DataDict)list.get(0); String ddvalue = dd.getDdvalue();
// 在Redis中设置数据字典的值
jedis.set(redisKey, ddvalue); return ddvalue;
} return "";
}
再JSP中的使用:
<label>
<input type="radio" name="sex" class="icheck" value="0" /> <dataDict:dataDictValue typeCode="sex" ddKey="0"/>
</label> <label>
<input type="radio" name="sex" class="icheck" value="1" /> <dataDict:dataDictValue typeCode="sex" ddKey="1"/>
</label> <label>
<input type="radio" name="sex" class="icheck" value="2" checked="checked"/> <dataDict:dataDictValue typeCode="sex" ddKey="2"/>
</label>
如果是用jqgrid类似这样的js插件来渲染的话,那么需要再额外自定义api接口供js或者其他应用调用:
{ name: 'sex', index: 'sex', width: 20, sortable: false,
formatter:function(cellvalue, options, rowObject) { var typeCode = "sex";
var ddkey = cellvalue;
var ddvalue = ""; $.ajax({
url: $("#hdnContextPath").val() + "/dataDict/queryDataDictValue.action",
type: "POST",
async: false,
data: {"typeCode": typeCode, "ddkey": ddkey},
success: function(data) {
if(data.status == 200 && data.msg == "OK") {
ddvalue = data.data;
} else {
console.log(JSON.stringify(data));
}
},
error: function (response, ajaxOptions, thrownError) {
Error.displayError(response, ajaxOptions, thrownError);
}
}); return ddvalue}
},
基本上就是这些用法了,具体我录制了一些视频,代码也上传到了github
http://www.itzixi.com/course/detail.shtml?courseId=17092078Y3009WX4