H2通用缓存加载(3)——通用配置

来源:互联网 发布:mac 终端 颜色 编辑:程序博客网 时间:2024/06/04 21:54

1.abstract  class     声明 初始化(init),创建h2缓存表(create),插入数据(insertData),初始化完成(inited),销毁(destroy)方法,并在类中存放共有方法

 

      AbstractH2LoadCache.java

package com.dyna.report.config.abstracts;

 

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.Iterator;

import java.util.Map;

 

import org.springframework.jdbc.core.RowMapper;

 

import com.dyna.report.config.enums.DataBaseType;

import com.dyna.report.config.tools.H2Column;

import com.dyna.report.config.tools.H2Table;

 

public abstract class AbstractH2LoadCache {

        protected TemplateFactory tf;

 

        public void setFc(TemplateFactory fc) {

               this.tf = fc;

        }

 

        protected H2Table table;

 

        public void setTable(H2Table table) {

               this.table = table;

        }

 

        /**

         * 判断传入的  表名称  在H2数据库中是否存在

         * @param tableName

         * @return

         */

        protected Boolean existsH2Table(String tableName) {

               String sql = "SELECT count(*) tableNum FROM INFORMATION_SCHEMA.TABLES where table_name = upper(?)";

               Integer num = tf.getJdbcTemplate(DataBaseType.H2).queryForObject(

                               sql, new Object[] { tableName }, new RowMapper<Integer>() {

                                      public Integer mapRow(ResultSet res, int arg1)

                                                     throws SQLException {

                                              Integer num = res.getInt("tableNum");

                                              return num;

                                      }

                               });

               if (num <= 0) {

                       return false;

               }

               return true;

        }

 

        /**

         * 根据配置列信息组装  创建H2数据库的sql语句

         * @param columns

         * @return

         */

        protected String splitTableColumns(Map<String,H2Column> columns){

               StringBuffer sb = new StringBuffer();

               String[] strclm = new String[columns.size()];

               Iterator it = columns.keySet().iterator();

               while(it.hasNext()){

                       String key = it.next().toString();

                       H2Column column = columns.get(key);

                       strclm[Integer.parseInt(column.getOrder())]=column.getKey()+" "+column.getType();

               }

               for(String clm :strclm){

                       sb.append(clm).append(",");

               }

               return sb.substring(0, sb.length()-1);

        }

        public abstract void init();

 

        public abstract void create();

 

        public abstract void insertData();

 

        public abstract void inited();

 

        public abstract void destroy();

}


2.  LoadH2Cache.java   ,在listener 中调用,执行H2缓存表的生成创建,插入数据,销毁缓存等

 

package com.dyna.report.config.tools;

 

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.Iterator;

import java.util.Map;

 

import org.apache.log4j.Logger;

import org.springframework.jdbc.core.RowMapper;

 

import com.dyna.report.config.abstracts.AbstractH2LoadCache;

import com.dyna.report.config.abstracts.TemplateFactory;

import com.dyna.report.config.enums.DataBaseType;

import com.dyna.report.config.exceptions.BussException;

import com.dyna.report.config.util.SysUtil;

 

public class LoadH2Cache {

        private static Logger logger = Logger

                       .getLogger(LoadH2Cache.class.getName());

        private TemplateFactory tc;

 

        public void setTc(TemplateFactory tc) {

               this.tc = tc;

        }

 

        /**

         * 创建H2缓存

         *

         * @param map

         */

        public void loadH2Map(Map map) {

               try {

                       if (map == null || map.size() <= 0) {

                               logger.error("h2数据库配置缺失,不能使用h2数据库缓存");

                       }

                       if (SysUtil.H2Cache.equalsIgnoreCase("n")) {

                               throw new BussException("h2缓存数据库功能关闭,请确认");

                       }

 

                       String sql = "SELECT count(*) usercount FROM INFORMATION_SCHEMA.USERS ";

                       try {

                               int num = tc.getJdbcTemplate(DataBaseType.H2).queryForObject(

                                              sql, new RowMapper<Integer>() {

                                                     public Integer mapRow(ResultSet res, int arg1)

                                                                     throws SQLException {

                                                             Integer num = res.getInt("usercount");

                                                             return num;

                                                     }

                                              });

                       } catch (org.springframework.jdbc.CannotGetJdbcConnectionException e) {

                               SysUtil.H2Cache = "G";

                               logger.error("h2初始化发生错误:" + e.getMessage() + ",不能使用h2数据库缓存");

                               e.printStackTrace();

                       }

 

                       Iterator it = map.keySet().iterator();

                       while (it.hasNext()) {

                               String key = it.next().toString();

                               H2Table table = (H2Table) map.get(key);

                               try {

                                      AbstractH2LoadCache h2cache = table.getLoadClass();

                                      h2cache.setFc(tc);

                                      h2cache.setTable(table);

                                      h2cache.init();

                                      h2cache.create();

                                      h2cache.insertData();

                                      h2cache.inited();

                                      logger.info("h2缓存初始化" + table.getText() + "完成");

                               } catch (BussException e) {

                                      logger.error("初始化h2 " + table.getText() + "缓存发生业务错误:"

                                                     + e.getMessage());

                                      e.printStackTrace();

                               } catch (Exception e) {

                                      logger.error("h2初始化发生错误:" + e.getMessage() + ",不能使用h2数据库"

                                                     + table.getText() + " 缓存");

                                      e.printStackTrace();

                               }

 

                               logger.debug("初始化好H2数据库表 name==" + table.getName() + " TEXT=="

                                              + table.getText());

                       }

                       SysUtil.H2Cache = "Y";

               } catch (BussException e) {

                       logger.error("初始化h2缓存发生业务错误:" + e.getMessage());

                       e.printStackTrace();

               } catch (Exception e) {

                       logger.error("h2初始化发生错误:" + e.getMessage() + ",不能使用h2数据库缓存");

                       e.printStackTrace();

               }

        }

 

        /**

         * 销毁H2缓存

         *

         * @param map

         */

        public void destroyH2Map(Map map) {

               try {

                       if (map == null || map.size() <= 0) {

                               logger.error("h2数据库配置缺失,不能使用h2数据库缓存");

                       }

                       if (SysUtil.H2Cache.equalsIgnoreCase("n")) {

                               throw new BussException("h2缓存数据库功能关闭,请确认");

                       }

 

                       String sql = "SELECT count(*) usercount FROM INFORMATION_SCHEMA.USERS ";

                       try {

                               int num = tc.getJdbcTemplate(DataBaseType.H2).queryForObject(

                                              sql, new RowMapper<Integer>() {

                                                     public Integer mapRow(ResultSet res, int arg1)

                                                                     throws SQLException {

                                                             Integer num = res.getInt("usercount");

                                                             return num;

                                                     }

                                              });

                       } catch (org.springframework.jdbc.CannotGetJdbcConnectionException e) {

                               SysUtil.H2Cache = "G";

                               logger.error("h2初始化发生错误:" + e.getMessage() + ",不能使用h2数据库缓存");

                               e.printStackTrace();

                       }

 

                       Iterator it = map.keySet().iterator();

                       while (it.hasNext()) {

                               String key = it.next().toString();

                               H2Table table = (H2Table) map.get(key);

                               try {

                                      AbstractH2LoadCache h2cache = table.getLoadClass();

                                       h2cache.setFc(tc);

                                      h2cache.destroy();

                                      logger.info("h2缓存销毁" + table.getText() + "完成");

                               } catch (BussException e) {

                                      logger.error("销毁h2 " + table.getText() + "缓存发生业务错误:"

                                                     + e.getMessage());

                                      e.printStackTrace();

                               } catch (Exception e) {

                                      logger.error("h2销毁发生错误:" + e.getMessage() + ",不能使用h2数据库"

                                                     + table.getText() + " 缓存");

                                      e.printStackTrace();

                               }

 

                               logger.debug("销毁H2数据库表 name==" + table.getName() + " TEXT=="

                                              + table.getText());

                       }

                       SysUtil.H2Cache = "Y";

               } catch (BussException e) {

                       logger.error("销毁h2缓存发生业务错误:" + e.getMessage());

                       e.printStackTrace();

               } catch (Exception e) {

                       logger.error("h2销毁发生错误:" + e.getMessage() + ",不能使用h2数据库缓存");

                       e.printStackTrace();

               }

        }

}


3.   H2Column.java

package com.dyna.report.config.tools;

 

import java.io.Serializable;

 

import com.dyna.report.config.abstracts.AbstractCommonPoJo;

 

public class H2Column extends AbstractCommonPoJo implements Serializable{

 

        private static final long serialVersionUID = 1L;

       

        private String key;

        private String text;

        private String tablename;

        private String type;

        private String order;

       

        public String getType() {

               return type;

        }

        public void setType(String type) {

               this.type = type;

        }

        public String getOrder() {

               return order;

        }

        public void setOrder(String order) {

               this.order = order;

        }

        public String getKey() {

               return key;

        }

        public void setKey(String key) {

               this.key = key;

        }

        public String getText() {

               return text;

        }

        public void setText(String text) {

               this.text = text;

        }

        public String getTablename() {

               return tablename;

        }

        public void setTablename(String tablename) {

               this.tablename = tablename;

        }

 

}


4.   H2Table.java 

 

package com.dyna.report.config.tools;

 

import java.io.Serializable;

import java.util.HashMap;

import java.util.Map;

 

import com.dyna.report.config.abstracts.AbstractCommonPoJo;

import com.dyna.report.config.abstracts.AbstractH2LoadCache;

 

public class H2Table extends AbstractCommonPoJo implements Serializable{

 

        private static final long serialVersionUID = 1L;

       

        private String name;

        private String text;

        private String database;

        private AbstractH2LoadCache loadClass;

        private Map<String,H2Column> columns = new HashMap<String, H2Column>();

       

        public String getName() {

               return name;

        }

        public void setName(String name) {

               this.name = name;

        }

        public String getText() {

               return text;

        }

        public void setText(String text) {

               this.text = text;

        }

        public String getDatabase() {

               return database;

        }

        public void setDatabase(String database) {

               this.database = database;

        }

        public AbstractH2LoadCache getLoadClass() {

               return loadClass;

        }

        public void setLoadClass(AbstractH2LoadCache loadClass) {

               this.loadClass = loadClass;

        }

        public Map<String, H2Column> getColumns() {

               return columns;

        }

        public void setColumns(Map<String, H2Column> columns) {

               this.columns = columns;

        }

       

}

 

5.  BeanHelper .java    

public class Beanhelper {

        private static Logger logger = Logger.getLogger(Beanhelper.class.getName());

 

        /**

         * 根据类全名 生成类

         * @param s

         * @return

         */

        public static Object getClass(String s) {

               try {

                       return Thread.currentThread().getContextClassLoader().loadClass(s)

                                      .newInstance();

               } catch (Exception e) {

               }

               try {

                       return Class.forName(s).newInstance();

               } catch (Exception e) {

                       throw new BussException(e.getMessage());

               }

        }

 

6.   ZgCodeLoadCache.java

 

package com.dyna.report.config.H2load;

 

import java.util.List;

 

import net.sf.json.JSONObject;

 

import org.apache.log4j.Logger;

 

import com.dyna.report.config.abstracts.AbstractH2LoadCache;

import com.dyna.report.config.control.CommonConfigDao;

import com.dyna.report.config.control.CommonRowMapper;

import com.dyna.report.config.enums.DataBaseType;

import com.dyna.report.config.exceptions.BussException;

 

public class ZgCodeLoadCache extends AbstractH2LoadCache {

        private static Logger logger = Logger.getLogger(ZgCodeLoadCache.class

                       .getName());

 

        public void init() {

               if (existsH2Table(table.getName())) {

                       throw new BussException("缓存表 name:" + table.getName() + " TEXT:"

                                      + table.getText() + "已经存在,请确认");

               }

        }

 

        public void create() {

               StringBuffer sb = new StringBuffer();

               sb.append(" create table ").append(table.getName()).append("(")

                               .append(splitTableColumns(table.getColumns())).append(")");

               logger.info("create table " + table.getText() + " sql:" + sb.toString());

               tf.getJdbcTemplate(DataBaseType.H2).update(sb.toString());

        }

 

        public void insertData() {

               int count = 0;

               String csq = " select aaa100,aaa102,aaa103,aaz093 from aa10 where  (aae031 is null or(length(aae031)=8 and to_date(aae031,'yyyymmdd')>sysdate)) order by aaz093";

               CommonConfigDao dao = new CommonConfigDao();

               dao.setTf(tf);

               List<JSONObject> jsons = dao.getTf()

                               .getJdbcTemplate(DataBaseType.valueOf(table.getDatabase().toUpperCase()))

                               .query(csq, new CommonRowMapper());

               String sql = "insert into " + table.getName() + " values (?,?,?,?)";

               for (int i = 1; i <= jsons.size(); i++) {

                       count = i;

                       JSONObject json = jsons.get(i - 1);

                       dao.getTf()

                                      .getJdbcTemplate(DataBaseType.H2)

                                      .update(sql, new Object[] { json.get("aaa102") ,

                                                     json.get("aaa103"), json.get("aaa100"), i});

 

               }

               csq = "select aaa027,aaa129,aab301 from aa13 ";

               jsons = dao.getTf()

                               .getJdbcTemplate(DataBaseType.valueOf(table.getDatabase().toUpperCase()))

                               .query(csq, new CommonRowMapper());

               for (int i = 1; i <= jsons.size(); i++) {

                       count++;

                       JSONObject json = jsons.get(i - 1);

                       dao.getTf()

                                      .getJdbcTemplate(DataBaseType.H2)

                                      .update(sql, new Object[] { json.get("aaa027") ,

                                                     json.get("aaa129"), "AAA027", json.get("aab301")});

 

               }

               csq = "select distinct aaa102,aaa103 from Aa23 aa23 where aae140 = 310  ";

               jsons = dao.getTf()

                               .getJdbcTemplate(DataBaseType.valueOf(table.getDatabase().toUpperCase()))

                               .query(csq, new CommonRowMapper());

               for (int i = 1; i <= jsons.size(); i++) {

                       count++;

                       JSONObject json = jsons.get(i - 1);

                       dao.getTf()

                                      .getJdbcTemplate(DataBaseType.H2)

                                      .update(sql, new Object[] { json.get("aaa102") ,

                                                     json.get("aaa103"), "AAC066", count

                                      });

 

               }

               logger.info("缓存表 name:" + table.getName() + " TEXT:" + table.getText()

                               + " 缓存完毕,共插入数据" + count + "条");

        }

 

        public void inited() {

        }

 

        public void destroy() {

        }

 

}


7.    JmCodeLoadCache.java

 

package com.dyna.report.config.H2load;

 

import java.util.List;

 

import net.sf.json.JSONObject;

 

import org.apache.log4j.Logger;

 

import com.dyna.report.config.abstracts.AbstractH2LoadCache;

import com.dyna.report.config.control.CommonConfigDao;

import com.dyna.report.config.control.CommonRowMapper;

import com.dyna.report.config.enums.DataBaseType;

import com.dyna.report.config.exceptions.BussException;

 

public class JmCodeLoadCache extends AbstractH2LoadCache {

        private static Logger logger = Logger.getLogger(JmCodeLoadCache.class

                       .getName());

 

        public void init() {

               if (existsH2Table(table.getName())) {

                       throw new BussException("缓存表 name:" + table.getName() + " TEXT:"

                                      + table.getText() + "已经存在,请确认");

               }

        }

 

        public void create() {

               StringBuffer sb = new StringBuffer();

               sb.append(" create table ").append(table.getName()).append("(")

                               .append(splitTableColumns(table.getColumns())).append(")");

               logger.info("create table " + table.getText() + " sql:" + sb.toString());

               tf.getJdbcTemplate(DataBaseType.H2).update(sb.toString());

        }

 

        public void insertData() {

               int count = 0;

               String csq = " select aaa100,aaa102,aaa103,aaz093 from aa10 where  (aae031 is null or(length(aae031)=8 and to_date(aae031,'yyyymmdd')>sysdate)) order by aaz093";

               CommonConfigDao dao = new CommonConfigDao();

               dao.setTf(tf);

               List<JSONObject> jsons = dao.getTf()

                               .getJdbcTemplate(DataBaseType.valueOf(table.getDatabase().toUpperCase()))

                               .query(csq, new CommonRowMapper());

               String sql = "insert into " + table.getName() + " values (?,?,?,?)";

               for (int i = 1; i <= jsons.size(); i++) {

                       count = i;

                       JSONObject json = jsons.get(i - 1);

                       dao.getTf()

                                      .getJdbcTemplate(DataBaseType.H2)

                                      .update(sql, new Object[] { json.get("aaa102") ,

                                                     json.get("aaa103"), json.get("aaa100"), i});

 

               }

               csq = "select aaa027,aaa129,aab301 from aa13 ";

               jsons = dao.getTf()

                               .getJdbcTemplate(DataBaseType.valueOf(table.getDatabase().toUpperCase()))

                               .query(csq, new CommonRowMapper());

               for (int i = 1; i <= jsons.size(); i++) {

                       count++;

                       JSONObject json = jsons.get(i - 1);

                       dao.getTf()

                                      .getJdbcTemplate(DataBaseType.H2)

                                      .update(sql, new Object[] { json.get("aaa027") ,

                                                     json.get("aaa129"), "AAA027", json.get("aab301")});

 

               }

              

               logger.info("缓存表 name:" + table.getName() + " TEXT:" + table.getText()

                               + " 缓存完毕,共插入数据" + count + "条");

        }

 

        public void inited() {

        }

 

        public void destroy() {

        }

 

}




 

 

 

0 0
原创粉丝点击