Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring data JPA generate id on database side only before create

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 ids on database side as I wish at all?

like image 285
Bohdan Petrenko Avatar asked Dec 08 '22 16:12

Bohdan Petrenko


1 Answers

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;
like image 95
Arnaud Avatar answered Jan 08 '23 11:01

Arnaud