Skip to content
Advertisement

How to create a sequence in JPA without creating it directly in the database

I am doing a service that gets data from a source and fetches them into my Database by using JPA. The id is generated by using sequence. I have created the sequence on my DB by using this command:

JavaScript

However, I don’t know how to create the sequence directly from my code.

Can anyone please help me to figure out this issue? Thank you so much!

My model class, modeltest.java:

JavaScript

My dao class, modeltestDao.java

JavaScript

EDIT: Btw, why i suppose to reset the sequence is each time i run the service (fetch data into database), the unique identifiers has increased by 1. For example, first time i run data, the id start with 1 and end with 10, second time i run data, the id start with 11 and end with 20. This problem only stop when i restart the server.

JavaScript

Other data do not change, but id. So i find a way to solve this is drop and recreate sequence each time i run saveData()

Advertisement

Answer

There’s a code smell in your proposal. Why do you need to avoid the database caching for the sequences in the first place? The whole point for a sequence is to generate unique identifiers, so you shouldn’t recreate the sequence while the application is running.

If you create the sequence in that method, imagine what happens when that method is called concurrently by multiple threads.

If your use case is valid, and you really need to delete all those records and reset the sequence, and you are using Oracle 12c, you can do something like this:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement