이야기박스
JPA. generate ddl-auto alphabetical order 본문
문제
Kotlin SpringBoot JPA를 통하여 자동으로 테이블을 생성한 경우, 컬럼 순서가 원하는 대로 들어가지 않습니다.
상황
application.yaml에 정의되어 있는 jpa 설정은 아래와 같습니다.
spring:
jpa:
database: mysql
hibernate:
ddl-auto: update
generate-ddl: true
show-sql: false
properties:
hibernate:
dialect: org.hibernate.dialect.MySQL55Dialect
테이블 정의 Entity는 아래와 같습니다.
원하는 컬럼 순서는 [ id -> name -> age ] 입니다.
@Entity
@Table(name = "sample")
data class Sample(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long,
@Column(name = "name", length = 30, nullable = false)
val name: String? = "",
@Column(name= "age")
val age: Int = 0
)
하지만 실제로 생성된 컬럼 순서는 아래와 같습니다.
[ id -> age -> name ], 알파벳 순서로 정렬된 것이 확인됩니다.
mysql> describe sample;
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | bigint | NO | PRI | NULL | auto_increment |
| age | int | YES | | NULL | |
| name | varchar(30) | NO | | NULL | |
+-------+-------------+------+-----+---------+----------------+
분석
이건 Hibernate의 내부 구조적 문제로, 당장 어노테이션을 활용하는 것 같은 간단한 해결 방법은 없다고 합니다.
Hibernate Community • View topic - Way to control column order with Ant schemaexport task
Is there any way to control the column order in the generated SQL using the Ant schemaexport task? The columns from each entity appear to be listed in alphabetical order and I would like them to be in the same order as they occur in the annotated entity so
forum.hibernate.org
조치
아래 옵션을 켜 두고 ddl 구문을 직접 초기 *.sql 형태로 작성해둡니다.
spring.sql.init.mode=always # Spring Boot >=v2.5.0
spring.datasource.initialization-mode=always # Spring Boot <v2.5.0
schema.sql 파일은 아래와 같이 구성하였습니다.
CREATE TABLE IF NOT EXISTS `sample`
(
id bigint NOT NULL AUTO_INCREMENT,
name varchar(30) NOT NULL,
age int DEFAULT NULL,
PRIMARY KEY (id)
);
이런 식으로 테이블 초기화를 하면 컬럼 순서를 원하는 바와 같이 구성할 수 있습니다.
mysql> describe sample;
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | bigint | NO | PRI | NULL | auto_increment |
| name | varchar(30) | NO | | NULL | |
| age | int | YES | | NULL | |
+-------+-------------+------+-----+---------+----------------+
후기
최근에 kotlin을 사용하면서 오랜만에 Spring을 다루고 있습니다. 종종 SpringBoot 콘텐츠도 올라올 것 같습니다.
'Programming Language > Spring' 카테고리의 다른 글
(작성중) Spring. HttpMessageConverters (0) | 2019.11.28 |
---|---|
(작성중) Spring Test & JUNIT (0) | 2019.11.15 |
Spring. SpringJDBC - ibatis 환경에서 Transaction 진행 (1) | 2019.10.18 |
Spring - Filter (0) | 2019.08.13 |
Spring JPA. Batch Insert 에러 (0) | 2019.03.28 |