Péťa Poliak
Péťa Poliak

Reputation: 411

Force hibernate to leave id empty

So I am using Postgres and Hibernate 4.2.2 and with entity like this

@Entity(name = "Users")
@Check(constraints = "email ~* '^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+[.][A-Za-z]+$'")
@DynamicInsert
public class Users {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "id_user",unique = true)
  @Index(name = "user_pk")
  private Integer idUser;

Hibernate still inserts some id that is already in the table, instead of leaving it emtpy for the database to fill it in. Also hibernate forces ids based on its cache not even checking the database whether it has the lates id.

How can I force it so I can leave id blank and let the database insert it?

First I thought it was because I was using int and that int is by default 0 but even when using object it just forces the id there from its cache.

So my goal is to let the database fill the ids instead of hibernate or at least Hibernate before filling it in to check the database for id first.

Upvotes: 1

Views: 581

Answers (2)

Kyle Laster
Kyle Laster

Reputation: 407

Seeding the data is the problem. However you can still seed with pure sequal and have the sequence "keep up".

1) Assure your primary key is of type SERIAL.

CREATE TABLE table_name(
    id SERIAL
);

2) Add this 'setval' line to assure the sequence is updated.

select setval('table_name_id_seq',COALESCE((select max(id) + 1 from table_name), 1));

Reference:

https://www.postgresqltutorial.com/postgresql-serial/

Upvotes: 0

Péťa Poliak
Péťa Poliak

Reputation: 411

So the error I was getting was
Caused by: org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "users_pkey" Detail: Key (id_user)=(1) already exists.
And it wasn't caused by Hibernate and caching but by import of data at creation of database, where I inserted with given ids eg:
INSERT INTO users(id_user,email,password,tag) VALUES (1,'[email protected]','***','Adpleydu');
and the sequence for generating wasn't updated so if I inserted with pure SQL via console I got the same error.

Upvotes: 1

Related Questions