Home  >  Article  >  Java  >  How to Map PostgreSQL Arrays to Java Arrays with Hibernate: A Guide to Numeric Array Mapping

How to Map PostgreSQL Arrays to Java Arrays with Hibernate: A Guide to Numeric Array Mapping

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-25 09:16:28225browse

How to Map PostgreSQL Arrays to Java Arrays with Hibernate: A Guide to Numeric Array Mapping

Mapping PostgreSQL Arrays with Hibernate

Introduction

Mapping PostgreSQL arrays to Java arrays via Hibernate can be challenging. This article addresses the common difficulties faced when attempting to map numeric arrays specifically.

Dependency Configuration

Setting up the following Hibernate Types Maven dependency is crucial:

<code class="xml"><dependency>
    <groupId>com.vladmihalcea</groupId>
    <artifactId>hibernate-types-52</artifactId>
    <version>${hibernate-types.version}</version>
</dependency></code>

Custom Type Definitions

Custom type definitions, such as the following, are required to map PostgreSQL arrays:

<code class="java">@TypeDefs({
    @TypeDef(
        name = "string-array", 
        typeClass = StringArrayType.class
    ),
    @TypeDef(
        name = "int-array", 
        typeClass = IntArrayType.class
    )
})</code>

The StringArrayType and IntArrayType classes are provided by the Hibernate Types project.

Example Mapping

Following the example SQL schema:

<code class="sql">CREATE TABLE sal_emp (name text, pay_by_quarter integer[]);</code>

A corresponding Java class would look like this:

<code class="java">@Entity(name = "SalEmp")
@Table(name = "sal_emp")
public class SalEmp implements Serializable {

    private String name;

    @Type(type = "int-array")
    @Column(name = "pay_by_quarter")
    private Integer[] payByQuarter;

    // Getters and setters omitted for brevity
}</code>

Inserting Entities

When inserting entities like:

<code class="java">SalEmp nullEmp = new SalEmp();
nullEmp.setName("Null Emp");
entityManager.persist(nullEmp);

SalEmp salEmp = new SalEmp();
salEmp.setName("Regular Emp");
salEmp.setPayByQuarter(new Integer[] {1, 2, 3});
entityManager.persist(salEmp);</code>

Hibernate will generate appropriate SQL statements for array insertion.

The above is the detailed content of How to Map PostgreSQL Arrays to Java Arrays with Hibernate: A Guide to Numeric Array Mapping. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn