Java应用自动产生database ID的方法
Java应用自动产生database ID的方法
我想利用应用来自动产生 database 的 ID 这个问题是大家经常会遇到的, 尤其当 application 会集群的时候,ID就显得更为复杂,在此给出一个我写的 id 生成类, 大家说说吧, 同时我也喜欢能够得到你关于这块更好的意见。。
public class IDUtils {
private static AtomicLong feedID;
private static AtomicLong itemID;
private static AtomicLong tagID;
private static AtomicLong commentID;
private static AtomicLong categoryID;
private static final String LOAD_FEED_ID =
"SELECT MAX(id) as maxID FROM rssmaFeed ";
private static final String LOAD_ITEM_ID =
"SELECT MAX(id) as maxID FROM rssmaItem";
private static final String LOAD_TAG_ID =
"SELECT MAX(id) as maxID FROM rssmaTag";
private static final String LOAD_COMMENT_ID =
"SELECT MAX(id) as maxID FROM rssmaComment";
private static final String LOAD_CATEGORY_ID =
"SELECT MAX(id) as maxID FROM rssmaCategory";
static {
feedID = new AtomicLong(getTableMaxID(LOAD_FEED_ID));
itemID = new AtomicLong(getTableMaxID(LOAD_ITEM_ID));
tagID = new AtomicLong(getTableMaxID(LOAD_TAG_ID));
commentID = new AtomicLong(getTableMaxID(LOAD_COMMENT_ID));
categoryID = new AtomicLong(getTableMaxID(LOAD_CATEGORY_ID));
}
private static long getTableMaxID(String sql) {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
if(rs.next()){
return rs.getLong("maxID");
}
} catch (SQLException e) {
LogUtils.error(e);
} finally {
try { if (pstmt != null) { pstmt.close(); } }
catch (Exception e) { LogUtils.error(e); }
try { if (con != null) { con.close(); } }
catch (Exception e) { LogUtils.error(e); }
}
return 0;
}
public static long getFeedID(){
return feedID.incrementAndGet();
}
public static long getItemID(){
return itemID.incrementAndGet();
}
public static long getTagID(){
return tagID.incrementAndGet();
}
public static long getCommentID(){
return commentID.incrementAndGet();
}
public static long getCategoryID(){
return categoryID.incrementAndGet();
}
}