java中數據字典的使用:

數據字典:數據庫中一個字段下存在多個值的狀況(type:1:肉類  2:素菜類  3:服裝類):java

分析:spring

1:這種狀況下每每須要新建一張表來對應type下面的字段,一般以---表名--字段名---字段下面的值--字段明細--具體描述,等組成。數據庫

例如:數據庫中app

2:數據字典的具體使用:ide

思路:至關於把上面dic這張表的全部數據查詢出來,放入到一個集合中(HashMap中------以鍵值對的形式存放),再經過key,value的形式把須要的值取出來ui

具體實現:spa

經過key取值:3d

model層:經過typeValue來實現type的具體明細:code

代碼:xml

package com.floor.shop.map;

import com.floor.shop.dao.IDicDao;
import com.floor.shop.model.Dic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.HashMap;
import java.util.List;

public class DicMap {
    @Autowired
    private static IDicDao dicDao;
   private static HashMap<String, String> hashMap = new HashMap<>();
//靜態方法在程序啓動的時候只加載一次,這樣爲了讓查詢方法只去數據庫查詢一次
   static {
       //獲取應用上下文對象
       ApplicationContext ctx = new ClassPathXmlApplicationContext("mapper/spring-config.xml");
       //獲取dicDao實例
       dicDao = ctx.getBean(IDicDao.class);
         queryDic();
   }
   //從數據庫中取值放入到HashMap中
     public static void queryDic(){
           List<Dic> dics = dicDao.queryAll();
           StringBuilder sb = new StringBuilder();
           for(int i=0;i<dics.size();i++){
               Dic dic = dics.get(i);
               String tableName = dic.getTableName();
               String fieldName = dic.getFieldName();
               String fieldValue = dic.getFieldValue();
               String key = tableName+"_"+fieldName+"_"+fieldValue;
               String value = dic.getFieldDetail();
               System.out.println(key+"="+value);
               hashMap.put(key,value);
           }
       }

//    static{
//          hashMap.put("product_type_1","肉類");
//        hashMap.put("product_type_2","蔬菜類");
//        hashMap.put("product_type_3","服裝類");
//        hashMap.put("product_type_4","零食");
//        hashMap.put("product_type_5","其餘");
//    }

    public static String getFieldDetail(String tableName,String fieldName,String fieldValue){
        StringBuilder sb = new StringBuilder();
        StringBuilder keySb = sb.append(tableName).append("_").append(fieldName).append("_").append(fieldValue);
        String key = keySb.toString();
        String value = hashMap.get(key);
        return value;
    }
}
View Code
相關文章
相關標籤/搜索