0

Is there any way that I can generate ID field as 4 digit number i.e from 1000 to 9999 in my Spring boot application. Current Id field looks like this:

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "EMP_ID", nullable = false)
public short getEmp_id() {
    return emp_id;
}

As of now id is getting generated from 1. But I wanted to get it generated starting from 1000 and incremented by 1 until 9999.

As suggest by Ishikawa in comments and by referring Sequence Generation from Sequence Generation did below changes:

@Id
@GenericGenerator(
        name = "empid-sequence-generator",
        strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
        parameters = {
                @Parameter(name = "sequence_name", value = "user_sequence"),
                @Parameter(name = "initial_value", value = "1000"),
                @Parameter(name = "increment_size", value = "1")
        }
)
@GeneratedValue(generator = "empid-sequence-generator")
@Column(name = "EMP_ID", nullable = false)
public short getEmp_id() {
    return emp_id;
}

but even after that when trying to save the emp getting the below exception:

com.microsoft.sqlserver.jdbc.SQLServerException: Invalid object name 'user_sequence'.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:262)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1624)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:594)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:524)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7194)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:2979)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:248)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:223)

NOTE: It's third party database so I can't do any schema/constraint changes.I need to handle this through java code only.

Manish
  • 1,274
  • 3
  • 22
  • 59
  • 1
    I think you can try to implement your own id generator like here https://stackoverflow.com/questions/47259048/how-to-generate-custom-id-in-jpa – Ishikawa Yoshi Jul 21 '20 at 17:16

1 Answers1

0

My bad. Forgot to uncomment below line in application.properties.

spring.jpa.hibernate.ddl-auto = update

After uncommenting when I reboot my application it created the "user_sequence".

Manish
  • 1,274
  • 3
  • 22
  • 59