Skip to content
Advertisement

Make a POST with JPA with existing data

I have the following problem, the thing is that I have an entity:

package com.innovart.cpve.user.persistence.entity;

import lombok.Data;

import javax.persistence.*;
import java.time.LocalDateTime;

@Entity
@Data
@Table(name = "CPVE_USERS")
public class User {

@Id
@Column(name = "IDUSERS")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long idUser;

@Column(name = "IDROLES")
private Long idRol;

@Column(name = "USERNAME")
private String username;

@Column(name = "EMAIL")
private String email;

@Column(name = "PHONE")
private String phone;

@Column(name = "NAME")
private String name;

@Column(name = "LAST_NAME")
private String lastName;

@Column(name = "PASSWORD")
private String password;

@Column(name = "COUNTRY")
private String country;

@Column(name = "CITY")
private String city;

@Column(name = "GRANTS")
private String grant;

@Column(name = "STATE_ACTIVE")
private Integer stateActive;

@Column(name = "REGISTRATION_DATE")
private LocalDateTime registrationDate;

}

The thing is that this back is connected to an Oracle DB, in which I already have a few registered users, but these are entered through a Mockaroo script, and when I try to save a new user through a service Rest throws me this error:

2021-12-22 11:03:53.156 ERROR 23148 --- [nio-8080-exec-3] o.a.c.c.C.[.[.[. 
[dispatcherServlet]      : Servlet.service() for servlet [dispatcherServlet] in context 
with path [/api] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause

oracle.jdbc.OracleDatabaseException: ORA-01400: cannot insert NULL into ("CPVE"."CPVE_USERS"."IDUSERS")

Of course I understand that the problem is that since I have records already created, Spring tries to create a new user, but it does not “know” that it has to start from PK 500 for example.

Could it be that there is some way that Spring automatically knows the data of where the PK of users goes and continues it?

Advertisement

Answer

The problem was that when using the “strategy = GenerationType.AUTO” Hibernate creates in my Oracle database a sequence called Hibernate_Sequence, which is what defines what the value of the “idUsers” will be, I decided as in the example, create your own sequence to take the count from the value that I decide.

@Id
@Column(name = "IDUSERS")
@GeneratedValue(
        strategy = GenerationType.SEQUENCE,
        generator = "sequence-generator"
)
@SequenceGenerator(
        name = "sequence-generator",
        sequenceName = "SEC_IDUSER",
        initialValue = 501,
        allocationSize=1
)
private Long idUser;

This is how the code of my entity would look, and now if it already allows me to save new users. <3 <3 <3 <3 Thank you all very much.

Advertisement