JPA Insert + Oracle Sequences example

A quick JPA + Oracle sequences example, for self reference.

1. Oracle Database

Issue the following SQL script to create a table and a sequence.


CREATE TABLE CUSTOMER(
	ID NUMBER(10) NOT NULL,
	NAME VARCHAR2(100) NOT NULL,
	EMAIL VARCHAR2(100) NOT NULL,
	CREATED_DATE DATE NOT NULL,
	CONSTRAINT CUSTOMER_PK PRIMARY KEY (ID)
);

CREATE SEQUENCE customer_seq
  MINVALUE 1
  MAXVALUE 9999999999
  START WITH 4
  INCREMENT BY 1;

2. JPA

In Java, add JPA annotations like this :

Customer.java

package com.mkyong.model;

import javax.persistence.*;
import java.util.Date;

@Entity
public class Customer {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "CUST_SEQ")
    @SequenceGenerator(sequenceName = "customer_seq", allocationSize = 1, name = "CUST_SEQ")
    Long id;

    String name;
    String email;

    @Column(name = "CREATED_DATE")
    Date date;

    //...
}

Download Source Code

References

  1. Oracle / PLSQL: Sequences (Autonumber)
  2. Spring Boot + Spring Data JPA + Oracle example

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
dhanushka
Guest
dhanushka

thanks

NAZIA TARANNUM
Guest
NAZIA TARANNUM

what version of oracle did you use? if 12c then sequence cannot be used i guess?