Francois
Francois

Reputation: 616

How to create an id generator in JPA from a table having only one column

I'm currently building a JPA model from an old database, and I need some advice. In this database, ids were generated from a table object_id having only one PK column called next_id. This next_id is incremented each time a new object was created by the Java software using it.

My goal is to use the same table to generate ids for the JPA model. Is it something possible? I tried to use

@GeneratedValue(strategy = GenerationType.TABLE, generator = "myGenerator")
@TableGenerator(name = "myGenerator", table = "object_id", valueColumnName = "next_id")

but it doesn't seem to work because the object_id table has only one column (no sequence name column).

I have the following limitations:

  1. The software I talked about previously will be used until its update is completed.
  2. This is a commercial software. Its development and use must go on. It's impossible to stop developing and maintaining it.
  3. This update may take at least a year. The update will be done progressively. Database and user interface will be updated first. Then the computation kernel will follow.
  4. Computation is launched from the user interface in a separate thread. Once the user interface is updated, the same computation kernel will be called from it until the kernel is also updated.
  5. Once the kernel update is complete, then it will be possible to use another type of id generation. Until then, the id generation in the JPA model must work like the one done by the software.
  6. The ids must be created the same way to avoid duplicate keys.
  7. I'm fully aware that the generating ids from a table with JPA is not the best option. But this is legacy code. I have to deal with it.

I forgot to mention that development of this software started in 2000. At that time, there was no tools like Hibernate or JPA. A persistence tool was developed from scratch and is still used today. The goal is to get rid of it and use more recent technology.

Any hints? Thanks in advance.

Upvotes: 0

Views: 1291

Answers (2)

Nicholas Hirras
Nicholas Hirras

Reputation: 2596

We had a situation where we had to maintain a legacy system inserting records, and build a new system inserting records into the same table, and wanted to use a sequence generator for the new system. We just made the new sequence generator generate negative numbers, that way there was no chance of collisions between the two. Might be an option for you?

Upvotes: 0

Kayaman
Kayaman

Reputation: 73528

You can create your own generator by using @GenericGenerator. That does it make it dependent on Hibernate though, but you don't have a lot of choice. Then customize the generation strategy so that only table name is used.

See Can @TableGenerator save the last used id in the table instead of the next available?

Upvotes: 1

Related Questions