Video in progress

Strong Middle 🐻 Hibernate and JPA

How do you map a PostgreSQL array column (`text[]`, `bigint[]`) in Hibernate 6, and when is that a good idea?

Hibernate 6 supports arrays as a plain basic type: for a String[] or List<String> field you add @JdbcTypeCode(SqlTypes.ARRAY) if needed. It's convenient for small values like tags that are read only together with the owner. If you need joins or an FK on the elements, a separate table is better.

📖 Answer

@Entity
class Article {
    @Id @GeneratedValue Long id;

    @JdbcTypeCode(SqlTypes.ARRAY)
    @Column(columnDefinition = "text[]")
    private List<String> tags = new ArrayList<>();
}

In Hibernate 5 you needed a library like hypersistence-utils for this, and in 6 it's built in. The array is stored in a single column, so unlike @ElementCollection there's no separate table or join, and a read is from a single row.

For searching you need native SQL or Hibernate's array functions:

select * from article where tags @> array['java'];
-- to make it fast:
create index idx_article_tags on article using gin (tags);

In Hibernate 6.4+ HQL also has functions like array_contains, but they work depending on the dialect, so I write the important searches as native and verify them in a test.

One subtle point with dirty checking: Hibernate compares the array/list as a whole and, if it changed, rewrites the whole column. That's not a problem for small arrays.

When I don't use it: when the elements reference another table (for example, tag_ids), since you can't put an FK inside an array; when there are hundreds of elements and they change individually and often; when the data might move to another database, since arrays are a PostgreSQL-specific feature.