日常项目中经常有这样的需求,即需要几个紧密相关的内容存储起来,例如,xxx省xxx市xxx区等等。
例如下图:
这些紧密相关的内容可能会经常增加或者减少某项内容,在数据库应用中,当然可以设计几个字段来存储或者设计一个专门的key-value表来存储这些可变内容,但是对于这类不会直接用条件进行检索的紧密关联的内容来讲,保存在一个字段traffic_description中似乎更为妥帖一点。既然要存储在一个字段中那么就涉及到如何分割和组装的问题。
一个比较直接的做法就是使用分号对每项值进行分割存储,这种方式属于一种平面的结构,还有一个更好的办法就是将这些字段组装成一个json 字符串,格式如{'key1':value1,'key2':['value2','value21']},这样就可以直接利用现成的对象存储方式来保存,当前就有很多第三方包对json提供了支持,如:java中提供了json-lib.jar,其他语言支持包见
www.json.org
下面提供一种简单的实现:
使用方式如下:
/**
* @return the shipmentType
*/
public int getShipmentType() {
return shipmentType;
}
/**
* @param shipmentType the shipmentType to set
*/
public void setShipmentType(int shipmentType) {
this.shipmentType = shipmentType;
}
/**
* @return the fullName
*/
public String getFullName() {
return fullName;
}
/**
* @param fullName the fullName to set
*/
public void setFullName(String fullName) {
this.fullName = fullName;
}
/**
* @return the mobile
*/
public String getMobileTel() {
return mobileTel;
}
/**
* @param mobile the mobile to set
*/
public void setMobileTel(String mobile) {
this.mobileTel = mobile;
}
/**
* @return the province
*/
public String getProvince() {
return province;
}
/**
* @param province the province to set
*/
public void setProvince(String province) {
this.province = province;
}
/**
* @return the city
*/
public String getCity() {
return city;
}
/**
* @param city the city to set
*/
public void setCity(String city) {
this.city = city;
}
/**
* @return the section
*/
public String getSection() {
return section;
}
/**
* @param section the section to set
*/
public void setSection(String section) {
this.section = section;
}
/**
* @return the address
*/
public String getAddress() {
return address;
}
/**
* @param address the address to set
*/
public void setAddress(String address) {
this.address = address;
}
/**
* @return the post
*/
public String getPost() {
return post;
}
/**
* @param post the post to set
*/
public void setPost(String post) {
this.post = post;
}
/**
* 邮寄
*
* @return
*/
public boolean isMail() {
return this.shipmentType == BY_MAIL_TYPE;
}
/**
* 不需要
*
* @author qingxu
* @since 2007-10-25下午04:48:12
*
* @return
*/
public boolean isNotNeed() {
return this.shipmentType == BY_NOTNEED;
}
public String getInvoiceTitle() {
return invoiceTitle;
}
public void setInvoiceTitle(String invoiceTitle) {
this.invoiceTitle = invoiceTitle;
}
}
@JsonField标注支持 基本类型和数组、collection类型域。
在从DB中load出traffic_description的值后
通过setValue()方法设置进去,那么所有的json域都会被填充好。同样的,如果填充了相应的json域,
在存储在数据库中时,可以调用getValue()得到字符串持久化到数据库中。
通过getValue()得到的字符串形式如下:
这种处理方式的好处是,可以方便的定义你自己要存储的内容,你所有做的仅仅是在新增一个field,然后在上面打上@JsonField标注即可。
而它的缺点也是明显的,1、这种方式明显增加了存储内容的长度 2、由于存储的key是属性的名称,如果名称不匹配也会找不到对应的值。3、如果要对其中的内容进行条件检索,只有进行文本匹配,如果有这种需求,这种方式不推荐。