Spring JdbcTemplate框架(二)——動態建表
阿新 • • 發佈:2019-02-04
本篇部落格使用Spring JdbcTemplate實現動態建表。前面介紹了,它封裝了資料庫的基本操作,讓我們使用起來更加靈活,下面來實戰。
1、準備工作
引入jar包
2、applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd"> <!-- JDBC 操作模板 --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <constructor-arg> <ref bean="dataSource"/> </constructor-arg> </bean> <!-- 配置資料庫連線 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/dynamic" /> <property name="username" value="root" /> <property name="password" value="123456" /> </bean> </beans>
3、程式碼
private static ApplicationContext context = null; //通過測試類測試 public static void main(String[] args) { context = new ClassPathXmlApplicationContext("applicationContext.xml"); Users user = new Users(); user.setUserName("liutengteng"); user.setUserPass("liutengteng"); int re = insertObject("users",user); System.out.println("================" + re + "===================="); } /** * 建立表,新增記錄 * @param tableName * @param obj * @return */ public static int insertObject(String tableName,Object obj){ int re = 0; try { JdbcTemplate jt = (JdbcTemplate)context.getBean("jdbcTemplate"); SimpleDateFormat format = new SimpleDateFormat("yyyy_MM"); String tname = tableName + "_" + format.format(new Date()); // 判斷資料庫是否已經存在這個名稱的表,如果有某表 則儲存資料;否則動態建立表之後再儲存資料 if(getAllTableName(jt,tname)){ re = saveObj(jt,tname,obj); }else{ re = createTable(jt,tname,obj); re = saveObj(jt,tname,obj); } } catch (Exception e) { e.printStackTrace(); } return re; } /** * 根據表名稱建立一張表 * @param tableName */ public static int createTable(JdbcTemplate jt,String tableName,Object obj){ StringBuffer sb = new StringBuffer(""); sb.append("CREATE TABLE `" + tableName + "` ("); sb.append(" `id` int(11) NOT NULL AUTO_INCREMENT,"); Map<String,String> map = ObjectUtil.getProperty(obj); Set<String> set = map.keySet(); for(String key : set){ sb.append("`" + key + "` varchar(255) DEFAULT '',"); } sb.append(" `tableName` varchar(255) DEFAULT '',"); sb.append(" PRIMARY KEY (`id`)"); sb.append(") ENGINE=InnoDB DEFAULT CHARSET=utf8;"); try { jt.update(sb.toString()); return 1; } catch (Exception e) { e.printStackTrace(); } return 0; } /** * 拼接語句,往表裡面插入資料 */ public static int saveObj(JdbcTemplate jt,String tableName,Object obj){ int re = 0; try{ String sql = " insert into " + tableName + " ("; Map<String,String> map = ObjectUtil.getProperty(obj); Set<String> set = map.keySet(); for(String key : set){ sql += (key + ","); } sql += " tableName ) "; sql += " values ( "; for(String key : set){ sql += ("'" + map.get(key) + "',"); } sql += ("'" + tableName + "' ) "); re = jt.update(sql); } catch (Exception e) { e.printStackTrace(); } return re; } /** * 查詢資料庫是否有某表 * @param cnn * @param tableName * @return * @throws Exception */ @SuppressWarnings("unchecked") public static boolean getAllTableName(JdbcTemplate jt,String tableName) throws Exception { Connection conn = jt.getDataSource().getConnection(); ResultSet tabs = null; try { DatabaseMetaData dbMetaData = conn.getMetaData(); String[] types = { "TABLE" }; tabs = dbMetaData.getTables(null, null, tableName, types); if (tabs.next()) { return true; } } catch (Exception e) { e.printStackTrace(); }finally{ tabs.close(); conn.close(); } return false; }
4、總結
通過這種方式,讓我們更加靈活的運用,但是也有弊端,如果系統的程式碼量很大,用最基本的這套框架就會有很多重複性的程式碼,這時就需要一層層的抽象,封裝。抽象之後讓程式碼的複用性更高。其實每一套框架也是抽象封裝來的,不斷的抽象封裝,讓我們的程式碼更靈活,質量更高。