简体   繁体   中英

How to implement auto-increment field other than id field?

I want to implement one auto increment field other than id field that starts with 1 and increase by 1 sequentially.

Code Sample :

@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
private String id; //Id primary key

@Column(name = "request_number", nullable = false, unique = true, updatable = false, insertable = false)
@GeneratedValue(generator = "sequence", strategy = GenerationType.AUTO)
private Long requestNumber; //Talking about this

So, here requestNumber should increase automatically every time when ever object create. And that should increase sequentially.

Example : First entry's requestNumber will start with 1 and next requestNumber will be assign with 2 and so on...

I know it is possible via java code but I am looking for JPA provide such flexibility.

@GeneratedValue is used only for simple primary keys, as per the javadoc:

The GeneratedValue annotation may be applied to a primary key property or field of an entity or mapped superclass in conjunction with the Id annotation. The use of the GeneratedValue annotation is only required to be supported for simple primary keys. Use of the GeneratedValue annotation is not supported for derived primary keys.

If you want to do it in JPA you can define a @PrePersist method like:

@PrePersist
void doPrePersist() {
    // Use EntityManager to create a native query
    // read next value from a sequence
    // set the field value
}

Another option would be to define the database column as IDENTITY but this will take care of auto incrementing outside of JPA eg the entity field won't be insertable and value won't be seen during entity persist operation.

Please note that SQL Server, and most databases, doesn't guarantee that there won't be gaps in the sequence. When a transaction that increments sequence is rolled back the value of the sequence is not, so you can end up with: 1, 2, 4, 5, 6, 10, ...

You have to declare a @SequenceGenerator annotation on your class (or field):

@SequenceGenerator(sequenceName = "MY_DB_SEQUENCE", name = "sequence")
public class MyClass {
    // keep as is
}

Note that the generator = "sequence" on @GeneratedValue points to the @SequenceGenerator with the name = "sequence"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM