1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

SpringbootでInsertができない? ERROR: duplicate key value violates unique constraint

Last updated at Posted at 2022-07-05

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

DB初期投入時に連番型のIDに手動でデータを入れてしまったことが原因。

insert.py
SQL='''
INSERT INTO users
(id, "password", username)
VALUES(1, '$2a$10$lzGogDHmrBAGt2vDX93mEee1GmGOPIk4g1TmG5xinWOVuk6GFE4ra', 'admin');
    '''

idの生成はPostgresSQLに任せないとおかしくなるので注意。

insert.py
SQL='''
INSERT INTO users
("password", username)
VALUES('$2a$10$lzGogDHmrBAGt2vDX93mEee1GmGOPIk4g1TmG5xinWOVuk6GFE4ra', 'admin');
    '''

ちなみにエンティティの定義は至って普通

User.java
@Entity
@Table(name = "users",
        uniqueConstraints = {
                @UniqueConstraint(columnNames = "username")
        })
public class User implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?