通过static代码块在类被首次加载时候执行一次这个特性,可以起到一个初始化加载的作用;
初始化查询数据库,执行loadSchoolOrigoInfo()查询数据库,后续查询只需要查找静态变量schoolOrigoInfo
中的数据。
import java.util.concurrent.ConcurrentHashMap;
public class SchoolOrigoManager {
@SuppressWarnings("unchecked")
private static ConcurrentHashMap schoolOrigoInfo;
static {
System.out.println("---------加载学校籍贯信息--------");
loadSchoolOrigoInfo();
}
/**
* 加载学校籍贯信息
*/
@SuppressWarnings("unchecked")
public static void loadSchoolOrigoInfo() {
DBConnection dbConnection = null;
try {
// 连接数据库
dbConnection = DBConnectionFactory.createDBConnection();
BizDataAdapter dataAdapter = new BizDataAdapter(dbConnection);
schoolOrigoInfo = new ConcurrentHashMap();
VOList schoolInfo = new VOList();
schoolInfo = dataAdapter.query("SchoolOrigoManager.schoolInfo", null);
VOList origoInfo = new VOList();
origoInfo = dataAdapter.query("SchoolOrigoManager.origoInfo", null);
schoolOrigoInfo.put("origo", origoInfo);
schoolOrigoInfo.put("school", schoolInfo);
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭数据库
if (dbConnection != null) {
dbConnection.close();
}
}
}
//获取学校籍贯信息
public static VOList getSchoolOrigoInfo(String type) {
VOList voList = new VOList();
voList = (VOList) schoolOrigoInfo.get(type);
if (voList == null)
return null;
return voList;
}