JdbcTemplate 动态创建表并添加数据

来源:互联网 发布:麒麟外推软件 编辑:程序博客网 时间:2024/05/16 10:26

之前写了一个 使用JDBC查询是否存在某表或视图,按月动态生成表 ,但是他并不能进行公用,使用时需要每个人都写自己的处理代码,为了方便使用,我写了一个公共的处理方法,仅供参考。

 

为了考虑大家项目的集成,获得JdbcTemplate我采用Spring配置,也为了方便大家直接运行,初始化Spring的方式是写的Main方法

 

主要思路是:

使用Spring配置JdbcTemplate

通过一个代理对象和数据库进行对应,这个对象除了id和一个tableName属性外和数据库的字段名称都是一致的

通过一个公共方法类来获得代理类有那些属性,用来创建表和新增时进行动态SQL的拼装

核心处理是,先看有么有该表,没有创建插入,有的话直接插入

 

首先配置Spring,大家都会的

 

Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:aop="http://www.springframework.org/schema/aop"  
  5.     xmlns:tx="http://www.springframework.org/schema/tx"  
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd  
  7.            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd  
  8.            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">  
  9.     <!-- 数据源 -->  
  10.     <bean id="dataSource"  
  11.         class="org.apache.commons.dbcp.BasicDataSource"  
  12.         destroy-method="close">  
  13.         <property name="driverClassName" value="com.mysql.jdbc.Driver" />  
  14.         <property name="url"  
  15.             value="jdbc:mysql://192.168.0.69:3306/cui?useUnicode=true&amp;characterEncoding=UTF-8" />  
  16.         <property name="username" value="root" />  
  17.         <property name="password" value="root" />  
  18.         <!-- 连接池启动时的初始值 -->  
  19.         <property name="initialSize" value="2" />  
  20.         <!-- 连接池的最大值 -->  
  21.         <property name="maxActive" value="2" />  
  22.         <!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->  
  23.         <property name="maxIdle" value="2" />  
  24.         <!--  最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->  
  25.         <property name="minIdle" value="2" />  
  26.         <property name="defaultAutoCommit" value="true" />  
  27.     </bean>     
  28.     <!-- JDBC 操作模板 -->  
  29.     <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">  
  30.         <constructor-arg>  
  31.             <ref bean="dataSource"/>  
  32.         </constructor-arg>  
  33.     </bean>         
  34.     <!-- 用于初始化获得Spring对象的类 -->  
  35.     <bean id="springfactory" class="com.SpringFactory"></bean>  
  36. </beans>  

 

com.SpringFactory对象是用来动态获取Spring管理对象的类,之前博客中提到过

 

Java代码  收藏代码
  1. package com;  
  2. import org.springframework.beans.BeansException;  
  3. import org.springframework.context.ApplicationContext;  
  4. import org.springframework.context.ApplicationContextAware;  
  5. /** 
  6.  * @说明 获得Spring管理对象 
  7.  * @author cuisuqiang 
  8.  * @version 1.0 
  9.  * @since 
  10.  */  
  11. public class SpringFactory implements ApplicationContextAware {  
  12.     private static ApplicationContext context;  
  13.     @SuppressWarnings("static-access")  
  14.     public void setApplicationContext(ApplicationContext applicationContext)  
  15.             throws BeansException {  
  16.         this.context = applicationContext;  
  17.     }  
  18.     public static Object getObject(String id) {  
  19.         Object object = null;  
  20.         object = context.getBean(id);  
  21.         return object;  
  22.     }  
  23. }  

 

这个类可以根据配置的对象ID来获得该对象的引用

 

我们还需要将参数中对象进行处理,获得对象的属性名称和对应的值,这里提供了一个公共方法,之前博客提到过,只是改动了一些

 

Java代码  收藏代码
  1. package com;  
  2. import java.lang.reflect.Field;  
  3. import java.lang.reflect.Method;  
  4. import java.util.HashMap;  
  5. import java.util.Map;  
  6. /** 
  7.  * @说明 对象操纵高级方法 
  8.  * @author cuisuqiang 
  9.  * @version 1.0 
  10.  * @since 
  11.  */  
  12. public class ObjectUtil {     
  13.     /**   
  14.      * 返回一个对象的属性和属性值 
  15.      */    
  16.     @SuppressWarnings("unchecked")     
  17.     public static Map<String,String> getProperty(Object entityName) {   
  18.         Map<String,String> map = new HashMap<String, String>();  
  19.         try {  
  20.             Class c = entityName.getClass();  
  21.             // 获得对象属性  
  22.             Field field[] = c.getDeclaredFields();     
  23.             for (Field f : field) {     
  24.                 Object v = invokeMethod(entityName, f.getName(), null);  
  25.                 map.put(f.getName(), v.toString());  
  26.             }  
  27.         } catch (Exception e) {  
  28.             map = null;  
  29.         }  
  30.         return map;  
  31.     }  
  32.     /** 
  33.      * 获得对象属性的值 
  34.      */  
  35.     @SuppressWarnings("unchecked")  
  36.     private static Object invokeMethod(Object owner, String methodName,  
  37.             Object[] args) throws Exception {  
  38.         Class ownerClass = owner.getClass();  
  39.         methodName = methodName.substring(01).toUpperCase()  
  40.                 + methodName.substring(1);  
  41.         Method method = null;  
  42.         try {  
  43.             method = ownerClass.getMethod("get" + methodName);  
  44.         } catch (SecurityException e) {  
  45.         } catch (NoSuchMethodException e) {  
  46.             return " can't find 'get" + methodName + "' method";  
  47.         }  
  48.         return method.invoke(owner);  
  49.     }     
  50. }  

 

传递一个对象,就会返回该对象的属性和属性值的Map

 

再来看一下对象实体类,要注意这个类一定不要和实际的类混了,因为你的业务对象类中可能会有一些额外的字段,这个会被公共方法的类解析而出问题的

 

Java代码  收藏代码
  1. package com;  
  2. /** 
  3.  * @说明 需要操作的实体 
  4.  * @author cuisuqiang 
  5.  * @version 1.0 
  6.  * @since 这个只能是代理对象,也就是说你需要和数据库同步对属性字段,实际上我们在表中还动态添加了一个 tableName 字段 
  7.  */  
  8. public class Users {      
  9.     private String userName;  
  10.     private String userPass;  
  11.     public String getUserName() {  
  12.         return userName;  
  13.     }  
  14.     public void setUserName(String userName) {  
  15.         this.userName = userName;  
  16.     }  
  17.     public String getUserPass() {  
  18.         return userPass;  
  19.     }  
  20.     public void setUserPass(String userPass) {  
  21.         this.userPass = userPass;  
  22.     }  
  23. }  

 

也就是说数据会有四个字段 id,userName,userPass,tableName,其中id和tableName是无需关心的

 

核心处理类我先发代码:

 

Java代码  收藏代码
  1. package com;  
  2. import java.sql.Connection;  
  3. import java.sql.DatabaseMetaData;  
  4. import java.sql.ResultSet;  
  5. import java.text.SimpleDateFormat;  
  6. import java.util.Date;  
  7. import java.util.Map;  
  8. import java.util.Set;  
  9. import org.springframework.context.ApplicationContext;  
  10. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  11. import org.springframework.jdbc.core.JdbcTemplate;  
  12. /** 
  13.  * @说明 进行测试 
  14.  * @author cuisuqiang 
  15.  * @version 1.0 
  16.  * @since 
  17.  */  
  18. public class DbTest {     
  19.     private static ApplicationContext context = null;     
  20.     public static void main(String[] args) {  
  21.         context = new ClassPathXmlApplicationContext("applicationContext.xml");       
  22.         Users user = new Users();  
  23.         user.setUserName("cuisuqinag@163.com");  
  24.         user.setUserPass("http://cuisuqiang.iteye.com/");         
  25.         int re = insertObject("users",user);  
  26.         System.out.println("---->" + re + "<----");  
  27.     }     
  28.     public static int insertObject(String tableName,Object obj){  
  29.         int re = 0;       
  30.         try {  
  31.             JdbcTemplate jt = (JdbcTemplate)context.getBean("jdbcTemplate");  
  32.             SimpleDateFormat format = new SimpleDateFormat("yyyy_MM");            
  33.             String tname = tableName + "_" + format.format(new Date());  
  34.             // 如果有某表  
  35.             if(getAllTableName(jt,tname)){  
  36.                 // 保存数据  
  37.                 re = saveObj(jt,tname,obj);  
  38.             }else{  
  39.                 // 动态创建表  
  40.                 re = createTable(jt,tname,obj);  
  41.                 // 保存数据  
  42.                 re = saveObj(jt,tname,obj);  
  43.             }             
  44.         } catch (Exception e) {  
  45.             e.printStackTrace();  
  46.         }         
  47.         return re;  
  48.     }     
  49.     /** 
  50.      * 保存方法,注意这里传递的是实际的表的名称 
  51.      */  
  52.     public static int saveObj(JdbcTemplate jt,String tableName,Object obj){  
  53.         int re = 0;  
  54.         try{              
  55.             String sql = " insert into " + tableName + " (";  
  56.             Map<String,String> map = ObjectUtil.getProperty(obj);  
  57.             Set<String> set = map.keySet();  
  58.             for(String key : set){  
  59.                 sql += (key + ",");  
  60.             }  
  61.             sql += " tableName ) ";               
  62.             sql += " values ( ";  
  63.             for(String key : set){  
  64.                 sql += ("'" + map.get(key) + "',");  
  65.             }  
  66.             sql += ("'" + tableName + "' ) ");  
  67.             re = jt.update(sql);          
  68.         } catch (Exception e) {  
  69.             e.printStackTrace();  
  70.         }         
  71.         return re;  
  72.     }     
  73.     /** 
  74.      * 根据表名称创建一张表 
  75.      * @param tableName 
  76.      */  
  77.     public static int createTable(JdbcTemplate jt,String tableName,Object obj){  
  78.         StringBuffer sb = new StringBuffer("");  
  79.         sb.append("CREATE TABLE `" + tableName + "` (");  
  80.         sb.append(" `id` int(11) NOT NULL AUTO_INCREMENT,");          
  81.         Map<String,String> map = ObjectUtil.getProperty(obj);  
  82.         Set<String> set = map.keySet();  
  83.         for(String key : set){  
  84.             sb.append("`" + key + "` varchar(255) DEFAULT '',");  
  85.         }         
  86.         sb.append(" `tableName` varchar(255) DEFAULT '',");  
  87.         sb.append(" PRIMARY KEY (`id`)");  
  88.         sb.append(") ENGINE=InnoDB DEFAULT CHARSET=utf8;");  
  89.         try {  
  90.             jt.update(sb.toString());  
  91.             return 1;  
  92.         } catch (Exception e) {  
  93.             e.printStackTrace();  
  94.         }  
  95.         return 0;  
  96.     }     
  97.     /** 
  98.      * 查询数据库是否有某表 
  99.      * @param cnn 
  100.      * @param tableName 
  101.      * @return 
  102.      * @throws Exception 
  103.      */  
  104.     @SuppressWarnings("unchecked")  
  105.     public static boolean getAllTableName(JdbcTemplate jt,String tableName) throws Exception {  
  106.         Connection conn = jt.getDataSource().getConnection();  
  107.         ResultSet tabs = null;  
  108.         try {  
  109.             DatabaseMetaData dbMetaData = conn.getMetaData();  
  110.             String[]   types   =   { "TABLE" };  
  111.             tabs = dbMetaData.getTables(nullnull, tableName, types);  
  112.             if (tabs.next()) {  
  113.                 return true;  
  114.             }  
  115.         } catch (Exception e) {  
  116.             e.printStackTrace();  
  117.         }finally{  
  118.             tabs.close();  
  119.             conn.close();  
  120.         }  
  121.         return false;  
  122.     }     
  123. }  

 

动态检查是否有某表和动态创建表之前博客有提到,最主要的就是根据对象属性Map进行动态SQL拼装

但是这里这个方法有很多的限制,比如创建字段的长度,新增时字段就必须有值,因为动态SQL会进行全量字段插入

另外,新增的字段表的名称是为了之后删除和查询详细做准备的

0 0