简体   繁体   中英

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 following 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM