package com.generate; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Random; import java.util.UUID; /** * 主键生成策略 * @author zzq * */ public class Generator { private static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS"); private static Random random = new Random(); private static NumberFormat nf = new DecimalFormat("000"); private static Map<String, IDTable> idTables = new HashMap<String, IDTable>(); /** * UUID主键生成策略 * @return 32位UUID */ public static String UUIDGenerator() { return UUID.randomUUID().toString(); } /** * COMB主键生成策略 * @return yyyyMMddHHmmssSS 17位时间 + 3位随机数 */ public static String COMBGenerator() { String datetime = sdf.format(new Date()); int end = random.nextInt(1000); nf.format(end); return datetime + end; } /** * 第三方数据表主键生成策略 * @param table 第三方主键表名 * @param keyColumnName 主键表识别主键字段名 * @param keyValue 主键表识别主键值 * @param valueColumnName 主键值字段名 * @return 主键值 */ public static synchronized long TableGenerator(String table, String keyColumnName, String keyValue, String valueColumnName) { String key = table + "/" + keyColumnName + "/" + keyValue + "/" + valueColumnName; IDTable idTable = idTables.get(key); if(null == idTable) { idTable = (new Generator()).new IDTable(); idTables.put(key, idTable); } return idTable.getValue(table, keyColumnName, keyValue, valueColumnName); } /** * 释放资源,将缓存的标识字段同步到数据库中 */ public static synchronized void TableGeneratorClose() { for(Iterator<String> iter = idTables.keySet().iterator(); iter.hasNext(); ) { String key = iter.next(); Generator.IDTable idTable = idTables.get(key); String[] str = key.split("/"); idTable.destory(str[0], str[1], str[2], str[3]); } } /** * 主键表(主要负责向数据库查询对应识别值的主键值) 加入缓存策略 * @author 朱志强 * */ public class IDTable { private long maxValue; private long nextValue; private static final long POOLSIZE = 10; private boolean isInit = false; public long getValue(String table, String keyName, String keyValue, String valueName) { if(false == isInit) { init(table, keyName, keyValue, valueName); isInit = true; } if(nextValue == maxValue) { query(table, keyName, keyValue, valueName); } nextValue++; return nextValue; } /** * 初始化资源,将属于与数据表中的标识字段同步 * @param table * @param keyName * @param keyValue * @param valueName */ public void init(String table, String keyName, String keyValue, String valueName) { StringBuffer sb = new StringBuffer("select ").append(valueName).append(" from ").append(table).append(" where ").append(keyName).append(" = '").append(keyValue).append("'"); Long id = DBUtil.executeQuery(sb.toString()); if(null != id) { nextValue = id; maxValue = id; } } public void query(String table, String keyName, String keyValue, String valueName) { StringBuffer sb = new StringBuffer("select ").append(valueName).append(" from ").append(table).append(" where ").append(keyName).append(" = '").append(keyValue).append("'"); Long id = DBUtil.executeQuery(sb.toString()); if(null == id) { sb = new StringBuffer("insert into ").append(table).append(" values('").append(keyValue).append("', ").append(POOLSIZE).append(")"); DBUtil.executeUpdate(sb.toString()); maxValue = POOLSIZE; nextValue = 0; } else { sb = new StringBuffer("update ").append(table).append(" set ").append(valueName).append("=").append(maxValue + POOLSIZE).append(" where ").append(keyName).append("='").append(keyValue).append("'"); DBUtil.executeUpdate(sb.toString()); maxValue += POOLSIZE; } } /** * 释放资源,将缓存中的数据同步到数据库中 * @param table * @param keyName * @param keyValue * @param valueName */ public void destory(String table, String keyName, String keyValue, String valueName) { StringBuffer sb = new StringBuffer("select ").append(valueName).append(" from ").append(table).append(" where ").append(keyName).append(" = '").append(keyValue).append("'"); Long id = DBUtil.executeQuery(sb.toString()); if(null != id) { sb = new StringBuffer("update ").append(table).append(" set ").append(valueName).append("=").append(nextValue).append(" where ").append(keyName).append("='").append(keyValue).append("'"); DBUtil.executeUpdate(sb.toString()); } } } public static void main(String[] args) throws Exception { long id = Generator.TableGenerator("idtable", "keyname", "t_user", "id"); System.out.println(id); id = Generator.TableGenerator("idtable", "keyname", "t_user", "id"); System.out.println(id); id = Generator.TableGenerator("idtable", "keyname", "t_person", "id"); System.out.println(id); id = Generator.TableGenerator("idtable", "keyname", "t_org", "id"); System.out.println(id); Generator.TableGeneratorClose(); } }
public class DBUtil { public static int executeUpdate(String sql) { Connection conn = null; Statement stmt = null; try { conn = ConnectionFactory.getConnection(); stmt = conn.createStatement(); return stmt.executeUpdate(sql); } catch(SQLException e) { throw new RuntimeException("更新失败", e); } finally { ConnectionFactory.close(stmt); ConnectionFactory.close(conn); } } public static Long executeQuery(String sql) { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { conn = ConnectionFactory.getConnection(); stmt = conn.createStatement(); rs = stmt.executeQuery(sql); boolean isReturn = rs.next(); if(isReturn == false) { return null; } return rs.getLong(1); } catch(SQLException e) { throw new RuntimeException("查询数据失败", e); } finally { ConnectionFactory.close(rs); ConnectionFactory.close(stmt); ConnectionFactory.close(conn); } } }
package com.generate; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; /** * 数据库连接工厂 * @author zzq * */ public class ConnectionFactory { private static String USERNAME; private static String PASSWORD; private static String URL; private static String DRIVERNAME; static { try { Properties prop = new Properties(); InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("jdbc.properties"); prop.load(is); USERNAME = prop.getProperty("username"); PASSWORD = prop.getProperty("password"); URL = prop.getProperty("url"); DRIVERNAME = prop.getProperty("drivername"); is.close(); Class.forName(DRIVERNAME); } catch (Exception e) { throw new RuntimeException("加载数据源配置文件失败", e); } } public static Connection getConnection() { Connection conn = null; try { conn = DriverManager.getConnection(URL, USERNAME, PASSWORD); } catch (Exception e) { throw new RuntimeException("获取数据库连接失败", e); } return conn; } public static void close(Connection conn) { if(null != conn) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void close(Statement stmt) { if(null != stmt) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void close(ResultSet rs) { if(null != rs) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } }