通过API POST插入时出现重复键错误

时间:2019-06-27 18:49:01

标签: java postgresql spring-boot

我在PostgreSQL上有BD,并且有很多表,但是我的问题是在表Usuario中。

我使用此脚本创建表:

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
);

然后我插入一个用户:

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

这没关系,现在我可以在Spring-boot上启动了

@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

现在,当我尝试使用API​​插入表Usuario时,调用此方法:

@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);
    }

我得到了错误:

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

这是因为我在初始化脚本上创建了id = 1的用户。

谁可以使用SQL插入表并在使用Spring-boot之后又没有出现此错误?

1 个答案:

答案 0 :(得分:0)

好吧,我看到@GeneratedValue有一个属性generator,所以我只是尝试添加我之前创建的序列生成器,并且它起作用了。因此,解决方案如下所示:

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