How to set and ID auto_increment with JPA using oracle database and without using oracle sequence.
Asked
Active
Viewed 907 times
1 Answers
0
You have the options specified in the following: http://docs.oracle.com/javaee/6/api/javax/persistence/GenerationType.html
In our application we use a table named SEQUENCE. You must, of course, create the table and insert a record with the sequence id and sequence number (starting point of the ids to be generated). You can then auto-increment this value by following the instructions laid out in the following article: http://www.oracle.com/technetwork/middleware/ias/id-generation-083058.html#table
To make the table in the example work by explicitly creating the table you could do the following:
create table ${your.schema}.ID_GEN (
ID_NAME varchar2(40),
ID_VAL long
);
Grant…
INSERT INTO ${your.schema}.ID_GEN (ID_NAME, ID_VAL)
VALUES (INV_GEN, 1);

neal
- 880
- 6
- 11
-
neal, thanks. I got it. `@Id @TableGenerator(name = "TABLE_GEN", table = "SCHEME.SERVICE_SEQ", pkColumnName = "SEQ_NAME", pkColumnValue = "TB.ID", valueColumnName = "SEQ_VALUE", allocationSize = 1) @GeneratedValue(strategy = GenerationType.TABLE, generator = "TABLE_GEN")` But now, I've a question. **Do you know how to get this sequence before insert an object? I need to response to client this id before insert it into db.** – Braian Jun 14 '17 at 14:49
-
The id is generated upon EntityManager.flush. See the following article in regards to retrieving the id: https://stackoverflow.com/questions/9732453/jpa-returning-an-auto-generated-id-after-persist. You would not want to generate ids for Entities if you're not persisting them. For instance, you might retrieve data from a REST call, map it to an Entity, then check the database to determine if that entity already exists. If so, and the "new" Entity.equals(existingEntity) you'd choose NOT to persist the "new" Entity. You would not want an id automatically generated. – neal Jun 16 '17 at 02:53