본문으로 바로가기

[JPA] postgresql array column 매핑

category JAVA/JPA 2024. 1. 21. 11:41

하고 싶은 것

postgresql 에 로또 번호가 담긴 int[] 컬럼이 존재한다. 

(int array column)

이걸 JPA 에 매핑하여 조회하고 싶다.

 

해결 방법

 

1. hibernate 버전을 확인한다. (아래 소스는 5버전 방법이다. 6버전은 찾아보시오.)

    public static void main(String[] args) {
        try {
            String hibernateVersion = org.hibernate.annotations.common.Version.getVersionString();
            System.out.println("Hibernate Version: "+ hibernateVersion);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Hibernate Version: 5.1.2.Final 로 확인되었다.

(gradle 에 hibernate-core:5.6.0.Final 으로 추가했으나 버전이 바뀌지는 않는다. 아무튼 상관 없다.)

 

 

2. 라이브러리 추가

implementation 'io.hypersistence:hypersistence-utils-hibernate-52:3.7.0'

vladmihalcea 라는 사람이 만든 라이브러리 (존경) 🙌🙌

https://github.com/vladmihalcea/hypersistence-utils

 

GitHub - vladmihalcea/hypersistence-utils: The Hypersistence Utils library (previously known as Hibernate Types) gives you Sprin

The Hypersistence Utils library (previously known as Hibernate Types) gives you Spring and Hibernate utilities that can help you get the most out of your data access layer. - GitHub - vladmihalcea/...

github.com

 

Readme 를 읽어보면 hibernate 버전에 맞는 libaray 버전을 알려준다.

 

 

3. Entity 에 @TypeDef, @Type 을 추가한다. 

(아래 방식은 5버전이므로 deprecated 표시가 된다. 6버전은 참고 사이트에 있다.)

import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;

import io.hypersistence.utils.hibernate.type.array.ListArrayType;

@Entity
@Table(schema = "money", name = "lotto")
@TypeDef(name = "list-array", typeClass = ListArrayType.class)
public class Lotto {
    @Type(type = "list-array")
    @Column(name = "number_list", columnDefinition = "integer[]")
    private List<Integer> numberList;
 }

 

 

4. 끝.

참고 : https://vladmihalcea.com/postgresql-array-java-list/

주의 : 반드시 hibernate 버전을 먼저 확인하고 진행하자.

 

※시간 걸린 이유 (반성)

1. numberList type을 Integer[] 이걸로 받으려고 하다보니 아래와 같은 에러가 났다...

Caused by: org.hibernate.MappingException: Could not instantiate Type: io.hypersistence.utils.hibernate.type.array.ListArrayType
java.lang.UnsupportedOperationException: The property number_list in ~ entity is not parameterized

난 그저 라이브러리 문제라고 생각하여 계속 버전 맞추는 작업만 했었다.

결국 List<Integer> 로 받으니까 바로 해결되더라.

괜히 매뉴얼 대로 따라하지 않아서 시간만 날렸다.

 

2. java.lang.NoClassDefFoundError: org/hibernate/query/BindableType
@Type 어노테이션에서 계속 에러 발생했다. 처음에 나의 Hibernate 버전이 5버전인지도 모르고 계속 6버전으로 시도했던 것...

 

안 될 때는 멋대로 바꾸지 말고 매뉴얼 그대로 따라해보자..