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. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
5 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
5 Comment authors
RakeshGuestGuestdhanushkaNAZIA TARANNUM Recent comment authors
newest oldest most voted
Guest
Guest
Guest

What if the sequence isn’t at the ID field. I have a table with a composite key and some another field that stores a sequence value. How would be possible to do it?

NAZIA TARANNUM
Guest
NAZIA TARANNUM

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

dhanushka
Guest
dhanushka

thanks

Guest
Guest
Guest

Thanks

Rakesh
Guest
Rakesh

Hi, This example is not working with Oracle 12c.