开发者

Generate unique key in Java to be used as primary key in Oracle tables

I am trying to get a string of length 15 to be used as primary key in database tables. The followi开发者_Python百科ng code in java returns some key with length 35

UUID.randomUUID().toString()
  1. Can I change it to return a key of the length 15 ?
  2. How to ensure thread safety?

Any help is greatly appreciated.


Why don't you make use of Oracle's sequence facility? You can't do anything better/safer using Java.

Edit: Your main concern is thus database performance. You didn't want to connect "again" to get the generated ID from the database. This concern is not needed if you just make use of connection pooling and just reuse the same connection to obtain the generated key immediately. Most JDBC drivers can give you the generated key back by Statement#getGeneratedKeys(). The newer JDBC drivers of Oracle supports it.

Here's a basic example:

Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet generatedKeys = null;

try {
    connection = database.getConnection();
    preparedStatement = connection.prepareStatement("INSERT INTO user (name, age) VALUES (?, ?)";
    preparedStatement.setString(user.getName());
    preparedStatement.setInteger(user.getAge());
    int affectedRows = preparedStatement.executeUpdate();
    if (affectedRows == 0) {
        throw new DAOException("Creating user failed, no rows affected.");
    }
    generatedKeys = preparedStatement.getGeneratedKeys();
    if (generatedKeys.next()) {
        user.setId(generatedKeys.getLong(1)); // Here's the magic.
    } else {
        throw new DAOException("Creating user failed, no generated key obtained.");
    }
} catch (SQLException e) {
    throw new DAOException(e);
} finally {
    close(connection, preparedStatement, generatedKeys);
}


randomUUID() does not create a real UUID (based on time, node, etc) but a pseudo random value. Assuming, the randomness is sufficiant, you should be able to pick any 15 chars from the 35 char UUID to create a random number - less strong compared to UUID but maybe sufficiant.

To really prevent clashes, you will need to maintain a sequence generator. If you don't want to use oracle, maybe a file based sequence generator is sufficiant? (next available sequence number is stored in a configuration file before it is used)


If you really need to generate your own keys, you could try JUG. You specifically asked for strings of length 15 - JUG cannot give you this. I'm not sure why this matters so assuming all you really care about is uniqueness, UUIDs are 128-bit (if I remember right) and are displayed in hexadecimal when string formatted.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜