Mohan
Mohan

Reputation: 741

creating sequence Id in hibernate

I wanted to generate sequence using hibernate tool ( pojo to sql). And definitely it works fine.

@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seqid-gen")
@SequenceGenerator(name = "seqid-gen", sequenceName = "RTDS_ADSINPUT_SEQ" )
@Column(name="id")  
public Long getId() {  
    return id;  
} 

This code generates below sql

create sequence RTDS_ADSINPUT_SEQ;  

The problem is I wanted to specify properties like

START WITH, INCREMENT BY, NOCACHE

and the final ddl script should be some thing like below

CREATE SEQUENCE  RTDS_ADSINPUT_SEQ  MINVALUE 1 MAXVALUE
999999999999999999 INCREMENT BY 1 START WITH 1 NOCACHE;

But as far I saw hibernate only support name, sequncename, allocationSize, initialvalue. My doubt is, if we use allocationSize = 1 & initialValue = 1 do we still need to mention "nocache". If so, do we have any kind of annotation for "nocache"?

Please advice me if I can include that properties as annotation in the pojo.

Upvotes: 3

Views: 19578

Answers (3)

Yoshita Mahajan
Yoshita Mahajan

Reputation: 453

We can generate sequence id using hibernate in below mentioned manner

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int uniqueid;

Upvotes: 0

0gam
0gam

Reputation: 1423

sequence use only oracle, postgreSQL, DB2, H2

I know two case.

(1)

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int idx;

Auto_increment, sequence object -> strategy = GenerationType.AUTO

(2) Your case.

Element Detail

public abstract String name (Required) A unique generator name that can be referenced by one or more classes to be the generator for primary key values.

public abstract String sequenceName (Optional) The name of the database sequence object from which to obtain primary key values. Defaults to a provider-chosen value. Default: hibernate_sequence

public abstract int initialValue (Optional) The value from which the sequence object is to start generating. Default:1

public abstract int allocationSize (Optional) The amount to increment by when allocating sequence numbers from the sequence. Default:50

DDL

create sequence RTDS_ADSINPUT_SEQ start with 1 increment by 1;

Entity

@Entity
@SequenceGenerator(
name = "seqid-gen", 
sequenceName = "RTDS_ADSINPUT_SEQ" 
initiaValue = 1, allocationSize = 1)
public class XXX {

   @Id
   @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seqid-gen")
   private long id;

    //getter, setter
}

Upvotes: 2

Lê Thọ
Lê Thọ

Reputation: 414

As i know we do not have such annotation properties. But ideally, you should create the sequence using your own SQL query instead using the default one generated by hibernate. When the sequence existed in database, Hibernate will not generate one, you can also disable hibernate ddl generation.

Upvotes: 0

Related Questions