通常我們的項目中有很多數據或者常量,在項目啟動后只需要加載一次,若通過普通的查詢方法,每次獲取都與數據庫交互必定影響效率;
故考慮用以下方法,僅第一次加載會查詢數據庫,再次獲取這些常量或數據時,會從緩存的Map中取值,明顯提升速度。
單例模式的一種實現方式:利用靜態HashMap和reload變量來實現。
1 //系統參數 2 3 public class SysParameter{ 4 private static final HashMap<String,SysParameter> tagMap = new HashMap<String,SysParameter>(); 5 6 private String key; // 參數名 7 private String value; // 參數值 8 9 private static final SysParameter NULL = new SysParameter("",""); 10 11 private static final String sql = "select key, value from TABLENAME where ChoSign ='Y' "; 12 private static boolean reload = false; 13 14 public String getKey(){ 15 return key; 16 } 17 18 public void setKey(String key){ 19 this.key = key; 20 } 21 public String getValue(){ 22 return key; 23 } 24 25 public void setValue(String Value){ 26 this.value = value; 27 } 28 29 // 構造函數 30 private SysParameter(){ 31 tagMap.clear(); 32 List<RowMap> sysParamList = DBSql.getMaps(sql, new HashMap<String, Object>());//此處可使用 Spring Jdbc Template實現數據庫查詢 33 34 if(sysParamList != null && sysParamList.size() > 0){ 35 for(RowMap rm : sysParamList){ 36 SysParameter sysParam = new SysParameter(rm.getString("key"),rm.getString("value")); 37 tagMap.put(sysParam.getKey(),sysParam); //存入HashMap中 38 } 39 } 40 raload = true; 41 } 42 43 // 根據key得到代碼類 44 public static SysParameter getSysParameterByKey(String key){ 45 if(!reload){ //僅第一次進入才調用構造方法,查詢數據 46 new SysParameter; 47 } 48 SysParameter sysParam = (SysParameter)tagMap.get(key); 49 if(sysParam == null){ 50 return NULL; 51 } 52 return sysParam; 53 } 54 55 // String.equalsIgnoreCase("Y"); 忽略大小寫匹配 56 57 // 帶參數的構造函數 58 private SysParameter(String key, String value){ 59 this.setKey(key); 60 this.setValue(valuee); 61 } 62 }