본문 바로가기
자바

[JDBC] DB PK변경 방법

by Hyeongjun_Ham 2024. 2. 7.

[JDBC] DB PK변경 방법

 

MariaDB에서 테이블 생성 후 pk를 바꿔야 하는 일이 생겼다.

 

방법은 다음과 같다.

 

1. JPA로 테이블 생성

2. 기존 PK 제거

3. 새로운 PK 생성

 

간단하다.

 

그러나 고려할게 몇 가지 있었는데 단계적으로 가면서 알아보자.

 

1. JPA로 테이블 생성

 

JPA로 테이블 생성은 특별하지 않다.

@Entity
@Table(name="test_table")
@Getter
@NoArgsConstructor
public class testTable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long idx;

    @Column(name="target", columnDefinition = "VARCHAR(50) comment '타겟' ")
    private String targetColumn;

    //...
    }

 

기본 PK가 idx인 여러 컬럼이 있는 테이블이다.

 

2. 기존 PK 제거

기존 키는 바로 지워지지 않는다.

 

JPA로 위와 같이 생성하게 되면 idx 컬럼에 AUTO INCREMENT 옵션이 들어가있다.

그런데 이 옵션이 있으면 바로 삭제가 안 된다.

 

그래서 두 가지 쿼리를 날려 기본 키를 제거한다.

 

1) 옵션 변경

ALTER TABLE test_table MODIFY idx INT NOT NULL DEFAULT 0;

 

default를 0으로 준 이유는 키를 바꾸고 데이터를 집어넣을 때 문제가 생겨 집어넣었다.

 

(idx 컬럼을 삭제하는 방법도 있을 것으로 추정됨)

 

2) PK 제거

ALTER TABLE test_table DROP PRIMARY KEY;

 

pk가 성공적으로 제거된다.

 

 

3. 새로운 PK 생성

쿼리는 다음과 같다.

ALTER TABLE test_table ADD PRIMARY KEY (target);

 

target인 컬럼에 PK를 부여하는 쿼리이다.

 

 


 

방법은 다음과 같고 내가 사용한 것을 간단히 정리하면

public void setPrimaryKey(String newPk) throws SQLException {
        // QueryUtil에 위의 쿼리 동적으로 만들게 해 놓음
        
        // 기존 키 제거 
        String preSettingQuery = QueryUtil.removeAutoIncrementAndSetDefaultZero(TableType.USER);
        String dropPKQuery = QueryUtil.dropPrimaryKey(TableType.USER);
        try (PreparedStatement preSettingStmt = dbConnection.prepareStatement(preSettingQuery);
             PreparedStatement dropPKStmt = dbConnection.prepareStatement(dropPKQuery)
        ) {
            preSettingStmt.executeUpdate();
            dropPKStmt.executeUpdate();

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        // 새로운 기본 키 생성
        String addPKQuery = QueryUtil.addPrimaryKey(TableType.USER, newPk);
        try (PreparedStatement dbStmt = dbConnection.prepareStatement(addPKQuery)
        ) {
            dbStmt.executeUpdate();

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

 

dbConnection 연결하는 것은 다른 작업에서 진행되었다.

newPk를 입력한 컬럼으로 PK설정을 할 수 있다.