English 中文(简体)
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.





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签