Id生成器--【DRP】

自增的id

思路:从数据库查出当前的id,然后+1

/**
 * 
 */
package com.bjpowernode.drp.util;

import java.awt.image.ConvolveOp;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @ClassName:IdGenerator
 * @Description:ID生成器
 * @author wm
 * @date 2016年1月15日下午6:41:06
 */
public class IdGenerator {
    /**
     * 根据表名生成该表的序列
     * @param tableName
     * @return 返回生成的序列
     */
    public static int generate(String tableName){
        //TODO:id 生成器
        String sql="select value from t_table_id where table_name=?";
        Connection conn =null;
        PreparedStatement pstmt=null;
        ResultSet rs=null;
        int value=0;
        try {
            conn=DbUtil.getConnection();
            pstmt=conn.prepareStatement(sql);
            pstmt.setString(1, tableName);
            rs=pstmt.executeQuery();
            if(!rs.next()){
                throw new RuntimeException();
            }
            value =rs.getInt("value");
            value++;
            modifyValueField(conn,tableName,value);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }finally{
            DbUtil.close(rs);
            DbUtil.close(pstmt);
            DbUtil.close(conn);
        }
        
        return value;
    }
    
    /**
     * 根据表名更新序列字段的值
     * @param conn
     * @param tableName
     * @param value
     * @throws SQLException 
     */
    private static  void modifyValueField(Connection conn,String tableName,int value) throws SQLException{
        String sql="update t_table_id set value=? where table_name=?";
        PreparedStatement pstmt=null;
        try {
            pstmt=conn.prepareStatement(sql);
            pstmt.setInt(1, value);
            pstmt.setString(2, tableName);
            pstmt.executeUpdate();
        } finally{
            DbUtil.close(pstmt);
        }
    }
    
    
    public static void main(String[] args){
        //完成测试
        int retValue=IdGenerator.generate("t_client");
        System.out.println(retValue);
    }
}
原文地址:https://www.cnblogs.com/wangmei/p/5135755.html