0

I have a MyClass entity with an auto increment id at the time of the project deployment I have an init.sql file to initialize the MY_CLASS table by adding two lines the problem when I use my web service REST to insert a new line in the MY_CLASS table I have an error message of duplicate key of id 1 for the first click and id 2 on the second click but after the POST goes without problems. To solve this problem I can add the following line in my init.sql file

ALTER SEQUENCE MY_CLASS_id_seq RESTART WITH 3;

My question: How can I configure my POST to persist the data with the last id because whenever I can insert data with SQL.

@Entity
@Cacheable
@Getter
@Setter
@Table(name = "MY_CLASS")
public class MyClass {
 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 private Long id;
 @NotNull
 private String label;
}
@RepositoryRestResource(collectionResourceRel = "clazz", path = "clazz")
public interface MyClassRepository extends PagingAndSortingRepository<MyClass, Long> {
}

init.sql

INSERT INTO public.MY_CLASS (label) values('label_1');
INSERT INTO public.MY_CLASS (label) values('label_2');
asked Dec 12, 2017 at 15:51

1 Answer 1

1

Wouldn't you use the sequence generator, would you?

public class MyClass {
 public static final String SEQUENCE_NAME = "MY_CLASS_id_seq";
 @Id
 @GeneratedValue(strategy = SEQUENCE, generator = SEQUENCE_NAME)
 @SequenceGenerator(name = SEQUENCE_NAME, sequenceName = SEQUENCE_NAME)
 private Long id;
 @NotNull
 private String label;
}
answered Dec 12, 2017 at 16:01
Sign up to request clarification or add additional context in comments.

2 Comments

your proposal solved my problem just the id jumped to 50 instead of using the last id 3. i do not understand why 50 and if i initialize my database with 50 lines in init.sql file would not ask problem
When Hibernate uses sequence generator it doesn't fetch the sequence value every time. Instead of it grabs a number of ids (50 by default) and manages them itself. Anyway you shouldn't worry if every number of sequence is used and there are gaps between them.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.