论坛首页 Java企业应用论坛

单例开发数据库主键生成策略,跨越数据库平台的主键生成方式

浏览 2655 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2007-12-15  
方向控制:我们使用一个表来存放所有所要管理表的主键和主键值.
表: keytable
create table keytable(
keyname varchar2(20) primary key,
keyvalue number(10) not null);


我们使用一个类来管理类的生成策略: Class KeyInfo
此类一次取出某一个主键的某一个缓冲值范围,每调用一次getNextKey()返回一个此主键的值,并且设定下一个主键值,取值策略如下: 值在范围内,取出值,如果值达到了缓冲范围的最大值,那么和数据库交互一下,生成下一个缓冲范围.在取出缓冲范围之前先更新一下数据库的主键值,避免取缓冲范围失败,下次再获得主键值已被使用.具体类如下:

package singleton.keySequence;

public class KeyInfo {
	
	private long minKey;
	private long maxKey;
	private int poolSize;
	private long nextKey;
	private String keyName;
	
	/**
	 * @param poolSize  键的缓冲长度
	 * @param keyName   键的名字
	 */
	public KeyInfo(int poolSize,String keyName){
		this.poolSize=poolSize;
		this.keyName=keyName;
		queryDB();
	}
	
	/**
	 * @return the value of nextKey 用于获得下一个键的方法
	 * 如果返回的键值大于键的上限,查询数据库重新进行对键的最大值,最小值和下一个返回键值的设定
	 */
	public long getNextKey(){
		if(nextKey>maxKey){
			queryDB();
		}
		return nextKey++;
	}
	/**
	 * 查询数据库重新进行对键的最大值,最小值和下一个返回键值的设定
	 */
	private void queryDB(){
		String updateSql="UPDATE KEYTABLE SET KEYVALUE=KEYVALUE+"
			+poolSize+" WHERE KEYNAME='"+keyName+"'";
		String querySql="select KEYVALUE FROM KEYTABLE WHERE KEYNAME='"+keyName+"'";
		
		JDBCTemplate.update(updateSql);
		
//		System.out.println(updateSql);
//		System.out.println(querySql);
		
		long valueFromDB=(Integer)JDBCTemplate.query(querySql);		maxKey=valueFromDB;
		minKey=maxKey-poolSize+1;
		nextKey=minKey;
	}
}


我们使用单例类来管理这些主键生成方式:
package singleton.keySequence;

import java.util.HashMap;
import java.util.Map;

public class KeyGenerator {
	
	private Map<String,KeyInfo> keyMap=new HashMap<String,KeyInfo>(10);
	private static final int POOL_SIZE=30;
	private static KeyGenerator keygen=new KeyGenerator();

	private KeyGenerator() {
	}
	
	public static KeyGenerator getInstance(){
		return keygen;
	}
	
	public long getNextKey(String keyName){
		if(keyMap.containsKey(keyName)){
			return keyMap.get(keyName).getNextKey();
		}else{
			KeyInfo keyInfo=new KeyInfo(POOL_SIZE,keyName);
			keyMap.put(keyName, keyInfo);
			return keyInfo.getNextKey();
		}
	}
}


JDBC访问数据库类 :
数据库工具类:JDBCConnectionFactory
管理Connection对象和资源关闭
/*
* (1)功能一:为用户提供连接对象
* (2)功能三:提供通用的关闭
*/
package common.db;
import java.sql.*;
import java.util.*;
import java.io.*;

public class JDBCConnectionFactory 
{
	static String url;
	static String user;
	static String password;
	
	//从文件中加载数据库的连接信息
	//目的:降低耦合度,即更换数据库时无需更改源代码。
	static
	{
		try
		{
		FileInputStream fis=new FileInputStream("common/db/dbtext");
		Properties pro=new Properties();
		pro.load(fis);
		
		url=pro.getProperty("url");
		user=pro.getProperty("username");
		password=pro.getProperty("password");
		
		fis.close();
		
		}catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	
	
	//功能一:
	public static Connection getConnection()
	{
		Connection conn=null;
		try
		{
			Class.forName("oracle.jdbc.driver.OracleDriver");
			conn=DriverManager.getConnection(url, user, password);
			
		}catch(Exception e){
			e.printStackTrace();
		}
		return conn;
	}
	
	//功能三:
	public static void close(Connection conn,ResultSet rs,Statement stmt)
	{
		try
		{
		if(conn!=null)
			conn.close();
		if(stmt!=null)
			stmt.close();
		if(rs!=null)
			rs.close();
		}catch(SQLException e){
			System.out.println(e.getMessage());
		}
	}
	
}


具体的数据库访问类
package common.db;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

public class JDBCTemplate {
	
	private static Connection conn=null;
	private static Statement stmt=null;
	private static ResultSet rs=null;

	public static void update(String updateSql) throws Exception{
		conn=JDBCConnectionFactory.getConnection();
		stmt=conn.createStatement();
		stmt.executeUpdate(updateSql);
		JDBCConnectionFactory.close(conn, null, stmt);
		conn=null;
		stmt=null;
	}
	
	public static Object query(String querySql)throws Exception{
		conn=JDBCConnectionFactory.getConnection();
		stmt=conn.createStatement();
		rs=stmt.executeQuery(querySql);
		int i=-1;
		while(rs.next()){
			i=rs.getInt(1);
			if(i!=-1)
				break;
		}
		JDBCConnectionFactory.close(conn, rs, stmt);
		conn=null;
		stmt=null;
		return i;
	}
}


以下是测试类
package singleton.keySequence;

public class ClientTest {
	
	public static void main(String[] args) throws Exception{
		
		KeyGenerator key=KeyGenerator.getInstance();
		for(int i=0;i<15;i++){
		System.out.println(key.getNextKey("person_id"));
		System.out.println(key.getNextKey("person_id"));
		}
	}
}

以上内容在MyEclipse 和Oracle9i上测试通过,
欢迎朋友相互交流,luoyuzj911@163.com
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics