I am using following code to define MyEntity
,
@Entity
@Table(name = "MY_TABLE")
public class MyEntity {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "MY_TABLE_ID")
private Integer myTableId;
@Column(name = "MY_TABLE_NM")
private String myTableName;
//Getters Setters
}
For the first POST
after my application starts, I create MyEntity
everything works fine, MY_TABLE_ID
starts with 1 and works as expected.
My issue is, If somebody inserts data manually before I do my POST
then I get duplicate key exception as myTableId
is entered as 1 which is already present.
My main problem is I can't create database sequence
for using GenerationType.SEQUENCE
now to resolve this as database can't be altered now.
I have tried various combinations of GenerationType
, TableGenerator
but I am unable to successfully tackle it.
Setting initialValue
to some larger number to avoid duplicate values can temporarily resolve my problem but I am unable to do it too.
If someone can help me with initialValue
with AUTO
or give me some other better solution without database changes will be great :)
As MY_TABLE_ID
is an identity column, following annotations will work.
@Entity
@Table(name = "MY_TABLE")
public class MyEntity {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY) // <-- IDENTITY instead of AUTO
@Column(name = "MY_TABLE_ID")
private Integer myTableId;
@Column(name = "MY_TABLE_NM")
private String myTableName;
//Getters Setters
}
The identity column will automatically assign an value as soon as the transaction is committed. You are not to set any values for an identity column, as its the job of the database to assign the values. Therefore you also don't need to think about any initial values (forget them completely for identity columns)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With