1

I am using spring-boot-starter-data-jpa in my Spring boot project to handle DB stuff.

I want to create a sequence in Oracle programmatically. I have seen many solution which create sequence using raw query but i want to create a sequence from the code. Is there anything i can do using JPA.

I also want to get this sequence number and return it to the caller.

Thanks in advance!!!

OldProgrammer
  • 11,263
  • 3
  • 25
  • 42
Awadesh
  • 2,860
  • 1
  • 17
  • 29

1 Answers1

0

First of all, you have to allow Hibernate (one of the JPA implementations available in spring-boot-starter-data-jpa) create DDL statements, so in application.properties:

spring.jpa.hibernate.ddl-auto=create

Note that it is not recommended for production.

Next, annotate your entity in following way:

@Entity
public class SomeEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "my_generator")
    @SequenceGenerator(name = "my_generator", sequenceName = "MY_SEQUENCE",  allocationSize = 1)
    private Long id;
    //...
}

Once your application will start, hibernate based on your ddl-auto configuration will create the sequence for you:

Hibernate: create sequence MY_SEQUENCE start with 1 increment by 1

You can read more about ddl-autoconfigurations here.

mkuligowski
  • 1,475
  • 1
  • 15
  • 26