Programming/Error

JPA 예약어로 인한 구문 오류 해결 방법 (check the manual that corresponds to your MariaDB server version for the right syntax to use near 'order …’)

Jan92 2023. 4. 19. 20:54

jpa 예약어로 인한 구문 오류 발생 시 해결하는 방법

jpa 예약어 구문 오류

jpa를 사용한 데이터 조회 작업 중 아래와 같은 'SQLSyntaxErrorException'이 발생했습니다.

해당 구문은 원래 정상적으로 동작하던 구문으로, 프로세스상의 필요에 의해 기존에 다른 이름으로 되어 있던 테이블 명만

'order'로 바꿨기 때문에 구문 상의 문제는 아닐 것이라고 생각했는데요.

 

 

You have an error in your SQL syntax;

java.sql.SQLSyntaxErrorException: (conn=14730) You have an error in your SQL syntax; 
check the manual that corresponds to your MariaDB server version for the right syntax to use near 'order order0_ inner join hospital hospital1_ on order0_.hospital_fk=hospital1...' at line 1

(order entity를 기준으로 한 조회에서 발생한 예외)

 

그리고 'order' 키워드가 mysql(및 mariadb)에서 예약어로 사용된다는 사실이 생각났으며, 결론적으로 해당 오류는 예약어로 사용되는 키워드가 테이블 명으로 사용되었기 때문이었습니다.

 

 

***

mysql에서 사용되는 예약어는 order 외에도 add, all, change, char, check, delete, exit, index 등, 200여 개가 넘는 예약어들이 있는데요. 자세한 내용은 아래 공식 문서를 참고해 주시면 좋을 것 같습니다.

 

 

* MySQL 8.0 Keywords and Reserved Words

https://dev.mysql.com/doc/refman/8.0/en/keywords.html

 

 


예약어 구문 오류 해결 방안

그렇다면 jpa에서 예약어로 인해 발생하는 구문 오류를 해결할 수 있는 방안은 무엇이 있을까요?

 

 

1. @Column 및 @Table 어노테이션 name 수정

//수정 전 오류 발생
@Column(name = "match")
@Table(name = "order")

//이스케이프 시퀀스
@Column(name = "\"match\"")
@Table(name = "\"order\"")

//백틱
@Column(name = "`match`")
@Table(name = "`order`")

첫 번째 방법은 @Column 및 @Table 어노테이션의 name 부분에 다음과 같은 \ 이스케이프 시퀀스를 통해 따옴표를 적용하는 방법과, ` 백틱(backtick)을 사용하는 방법이 있습니다.

 

 

2. hibernate 설정 추가

//application.properties
jpa.properties.hibernate.auto_quote_keyword=true

//application.yml
jpa:
    properties:
        hibernate:
            auto_quote_keyword: true

두 번째 방법은 hibernate 설정 값을 추가하는 방법입니다.

해당 설정은 모든 예약어에 대해 따옴표를 추가하는 설정이며, properties 또는 yml에 위와 같이 적용하면 오류가 발생하지 않습니다.