4

Question: Is it possible to generate sequence number not using select someSequence from dual; ?

Problem : @GeneratedValue and @SequenceGenerator by default is using select someSequence from dual; to get nextval for my id. But my user doesn't have such rights to select from the dual table so I can use only id = sequence.nextval, but I don't know how to use this in Entity class. Or how should I pass id value to Entity constructor like sequence.nextval?

Usage: Oracle DB, CrudRepository, save() method.

D1'
  • 81
  • 1
  • 9
  • can you make your question clearer please .. if you mean you want to construct a new opject you should just not send id and it will automatically generate it. – maha Sep 05 '18 at 07:16
  • as stated in the question I am using @SequenceGenerator to generate my id, this calls select mySequence from dual; (background process). But I want to get my id using sequence.nextval not using select. – D1' Sep 05 '18 at 07:26
  • define the database used, and the JPA provider. JPA provides many different strategies to use, and SEQUENCE is but one. –  Sep 05 '18 at 07:43

3 Answers3

5

You need to first create the sequence in Oracle:

CREATE SEQUENCE USER_SEQUENCE START WITH 1 INCREMENT BY 10;

Then annotate your class to look like this:

@Entity
@SequenceGenerator(name="USER_SEQUENCE_GENERATOR", sequenceName="USER_SEQUENCE", initialValue=1, allocationSize=10)
public class User {
    @Id
    @Column(name="USER_ID")
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="USER_SEQUENCE_GENERATOR")
    private Long userId;
}
sechanakira
  • 243
  • 3
  • 11
1

I think you would need to write yout own strategy and use the GenericGenerator annotation. This answer might be helpful for you: link

KaPrimov
  • 11
  • 3
0

You can insert id with the help of below query:

select max(id) from <<tableName>>;

If you cannot select from dual table , then you can query your own table, find the max id, increment it by 1 and assign it as the new id.

codeLover
  • 2,571
  • 1
  • 11
  • 27
  • Yes this can be an option, but I want to use sequence.nextval, because in the future I won't make incremented id. – D1' Sep 05 '18 at 07:23