In my application I'm using String data JPA with PostgreSQL. And for all entities in my application I'm looking for the way, to generate ids purely on the database side.
So, for example, here my currently working version:
@Entity
@Table(name = "permissions")
public class PermissionEntity {
@Id
@SequenceGenerator(name="permSeq", sequenceName="perm_id_seq", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="permSeq")
private Short id;
...........
}
I'm using allocationSize = 1
to avoid conflicts, because I'll have multiple instances of the application, that will work with the same database.
But in this case each time before create permission
, application makes request to the database perm_id_seq
sequence to receive the next value. I wanna create id
purely on database side, like in case with jdbc template
. To do that I set default value for the id
= nextval('perm_id_seq'::regclass)
and modified my code:
@Entity
@Table(name = "permissions")
public class PermissionEntity {
@Id
private Short id;
...........
}
Now it throws an exception when I'm trying to save entity:
org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save()
The reason why is clear for me. But, can somebody tell me, is it possible to generate id
s on database side as I wish at all?
Use GenerationType.IDENTITY
for your id, this will tell hibernate that the id of the identity column will be generated on the DB side :
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Short id;
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