我在 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)
OT 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() {
}
我收到错误:
Caused by: org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "usuario_pkey" Detail: Key (id)=(1) already exists.
这是因为我在初始化脚本中创建了 id=1 的用户。
在使用 Spring-boot 之后,我可以使用 SQL 将谁插入到表中而不会出现此错误?
喵喔喔
相关分类