postgreSQL array관련

BACK-END 2023. 9. 24. 18:29

postgreSQL에서 array필드를 query할 땐 아래처럼 하면 된다.
(tags가  TEXT[] 필드일 때 가정..==>  INSERT시에는 ARRAY['tag1', 'tag2']) 로 삽입.

 

== MyBatis. xml ===

<select id="getTags" resultType="string">
    SELECT array_agg(tag) AS tags
    FROM (SELECT unnest(tags) AS tag FROM posts) AS subquery
</select>

 

== java 코드 ==

public interface TagMapper {
    List getTags();
}

 

SqlSession sqlSession = sqlSessionFactory.openSession();
try {
    TagMapper tagMapper = sqlSession.getMapper(TagMapper.class);
    List<String> tags = tagMapper.getTags();
    
    // 결과(tags)를 처리
} finally {
    sqlSession.close();
}

 

Posted by yongary
,