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');
1 Answer 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;
}