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 (ie 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.
This will use the next value from your sequence P_REC_ID_SEQUENCE
.
This also depends upon what database you're using. You can define Sequences in Postgres
but not MySQL
.
If you are using MYSQL
then you can use Auto-Incremement
but you will not need to define the sequence .
If you're using ORACLE
database you define sequence as
CREATE SEQUENCE emp_sequence
INCREMENT BY 1
START WITH 1
Now, if the current sequence value is 100 then the next one will be 101. I hope it makes sense.
链接地址: http://www.djcxy.com/p/90892.html上一篇: 在多列上使用投影