SantiSori
SantiSori

Reputation: 411

Error duplicate key when insert via API POST

i have a BD on PostgreSQL and i have many tables, but my problem is at table Usuario.

I create the table with this script:

CREATE SEQUENCE usuario_id_seq;

CREATE TABLE public.usuario
(
   id               BIGINT NOT NULL DEFAULT nextval ('usuario_id_seq'::regclass),
   administrador    BOOLEAN NULL,
   password         CHARACTER VARYING (20) NOT NULL,
   username         CHARACTER VARYING (40) NOT NULL,
   CONSTRAINT usuario_pkey PRIMARY KEY (id)
      NOT DEFERRABLE INITIALLY IMMEDIATE,
   CONSTRAINT uk_863n1y3x0jalatoir4325ehal UNIQUE (username)
      NOT DEFERRABLE INITIALLY IMMEDIATE
);

And I insert one user with:

Insert into usuario (username, password, administrador) values ('prueba', '1234', false);

This goes ok, now i have on Spring-boot this:

@Entity
@Table(name = "usuario")
public class Usuario implements Serializable {

    @Id
    @GeneratedValue
    private Long id;

    @NotNull
    @Size(max = 40)
    @Column(name = "username", unique = true)
    private String username;

    @NotNull
    @Size(max = 20)
    @Column(name = "password")
    private String password;

    @Column(name = "administrador")
    private boolean administrador;

    @ManyToMany(cascade = {
            CascadeType.ALL
    })
    @JoinTable(name = "usuario_alerta",
    joinColumns = {@JoinColumn(name = "id_usuario", referencedColumnName = "id")},
    inverseJoinColumns = {@JoinColumn(name = "id_alerta", referencedColumnName = "id")})
    private Set<Alerta> alertasUsuario;

    @ManyToMany(cascade = {
            CascadeType.ALL
    })
    @JoinTable(name = "usuario_producto",
    joinColumns = {@JoinColumn(name = "id_usuario", referencedColumnName = "id")},
    inverseJoinColumns = {@JoinColumn(name = "id_producto", referencedColumnName = "id")})
    private Set<Producto> productosUsuario;

    // Hibernate requires a no-arg constructor
    public Usuario() {

    }

    public Usuario(String username, String password, boolean administrador) {
        this.username = username;
        this.password = password;
        this.administrador = administrador;
    }

..... Getters and Setters

Now, when i try to insert into table Usuario using API, calling to this:

@PostMapping("/usuario")
    ResponseEntity<Usuario> newUser(@ModelAttribute Usuario usuario) {
        Usuario user =  usuarioRepository.save(usuario);

        if(user != null)
            return new ResponseEntity<Usuario>(user, HttpStatus.CREATED);

        return new ResponseEntity<Usuario>(user, HttpStatus.BAD_REQUEST);
    }

I get the error:

Caused by: org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "usuario_pkey" Detail: Key (id)=(1) already exists.

And this is because i create the user with id=1 ont the init script.

Who can i insert into a table using SQL and after using Spring-boot without get this error?

Upvotes: 0

Views: 504

Answers (1)

SantiSori
SantiSori

Reputation: 411

Ok, i saw that @GeneratedValue has a atribute generator so I just try to add the sequence generator that i had created before and it works. So, the solution was put this line like:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY, generator="usuario_id_seq")
private Long id;

Upvotes: 1

Related Questions