论坛首页 入门讨论版 Hibernate

大家帮讨论一下利用主键表生成主键的问题

浏览 113 次
该帖已经被评为新手帖
作者 正文
最后更新时间:2008-07-04
我还是比较喜欢用主键表来生成主键,可是我比较担心线程同步的问题,下面是我的一个单例实现,会不会出现线程的问题:

public final class DBHelper {
private static TransactionContext transactionContext;

private static DBHelper m_Instance = new DBHelper();

private static Object obj = new Object();

private DBHelper() {
}

public static synchronized DBHelper getInstance() {
transactionContext = new TransactionContext();
return m_Instance;
}

public static final int getNextId(String table) throws ApplicationException {
synchronized (obj) {
String selectStatement = "select id from ecjtu_tableprikey where TableName='" + table + "'";
String updateStatement = "update ecjtu_tableprikey set id = id + 2 where TableName='" + table + "'";
PreparedStatement prepSelect = null;
PreparedStatement prepUpdate = null;
ResultSet rs = null;
Connection con = null;
int i;
try {
transactionContext.beginTran(true);
con = transactionContext.getDBConnection();
prepUpdate = con.prepareStatement(updateStatement);
prepUpdate.executeUpdate();
prepSelect = con.prepareStatement(selectStatement);
rs = prepSelect.executeQuery();
rs.next();
i = rs.getInt(1);
transactionContext.commitTran();
} catch (SQLException e) {
throw new ApplicationException("产生数据表" + table + "主键错误!!");
} finally {
transactionContext.closeResultSet(rs);
transactionContext.closeStatement(prepSelect);
transactionContext.closeStatement(prepUpdate);
transactionContext.closeConnection();
}
if (i <= 0) {
throw new ApplicationException("产生数据表" + table + "主键错误!!");
}
return i;
}
}

private static void log(String s) {
System.out.println(s);
}

}
   
最后更新时间:2008-07-04
主键这东西生成的比较多的话
可以一次性update ecjtu_tableprikey set id = id + 100
等这个100都用完了 在去也是不错的选择
   
0 请登录后投票
最后更新时间:2008-07-04
String selectStatement = "select id from ecjtu_tableprikey where TableName='" + table + "'";

⇒ 

String selectStatement = "select id from ecjtu_tableprikey where TableName='" + table + "' for update";
   
0 请登录后投票
论坛首页 入门讨论版 Hibernate

跳转论坛:
JavaEye推荐