Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA with SequenceGenerator and GeneratedValue

I have a code which uses JPA annotations to generate DB primary key.A DB sequence is used to generate the PK.Am using Oracle DB

@Id
@Column(name = "rec_id", scale = 0)
@GeneratedValue(generator = "RecIdSequence", strategy = GenerationType.SEQUENCE)
@SequenceGenerator(name = "RecIdSequence", sequenceName = "P_REC_ID_SEQUENCE")
public Long getRecordId() {
    return outboundPackageRecordId;
}

Now my understanding of this is: sequence id returned by DB sequencer is used as rec_id. IS this correct?

DOC says:

The Sequence Strategy The sequence strategy consists of two parts - defining a named sequence and using the named sequence in one or more fields in one or more classes. The @SequenceGenerator annotation is used to define a sequence and accepts a name, an initial value (the default is 1) and an allocation size (the default is 50). A sequence is global to the application and can be used by one or more fields in one or more classes. The SEQUENCE strategy is used in the @GeneratedValue annotation to attach the given field to the previously defined named sequence:

@Entity
@SequenceGenerator(name="seq", initialValue=1, allocationSize=100) // Define a sequence - might also be in another class:
public class EntityWithSequenceId {
    // Use the sequence that is defined above:
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq")
    @Id long id;
}

Unlike AUTO and IDENTITY, the SEQUENCE strategy generates an automatic value as soon as a new entity object is persisted (i.e. before commit). This may be useful when the primary key value is needed earlier. To minimize round trips to the database server, IDs are allocated in groups. The number of IDs in each allocation is specified by the allocationSize attribute. It is possible that some of the IDs in a given allocation will not be used. Therefore, this strategy does not guarantee there will be no gaps in sequence values.

like image 795
user93796 Avatar asked Dec 05 '25 14:12

user93796


1 Answers

Use generation type as AUTO instead SEQUENCE on primary key column.

@GeneratedValue(strategy = GenerationType.AUTO, generator = "generator")
@SequenceGenerator(name="generator", sequenceName="DB_SEQ_NAME")
like image 165
SreeNath Avatar answered Dec 08 '25 04:12

SreeNath



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!