Home >Java >javaTutorial >How to Map PostgreSQL Arrays to Java Arrays Using Hibernate?

How to Map PostgreSQL Arrays to Java Arrays Using Hibernate?

Linda Hamilton
Linda HamiltonOriginal
2024-10-25 00:31:02548browse

How to Map PostgreSQL Arrays to Java Arrays Using Hibernate?

Mapping PostgreSQL Array to Java Array using Hibernate

When attempting to map a PostgreSQL numeric array to a numeric array in Java via Hibernate, you may encounter an exception. This can be resolved by following these steps:

Maven Dependency

Add the following dependency to your project's pom.xml configuration file:

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

Hibernate Types

Define custom Hibernate types for the array columns:

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

Entity Mapping

Map the entity fields to the PostgreSQL array columns using these custom types:

<code class="java">@Type( type = "string-array" )
@Column(
    name = "sensor_names", 
    columnDefinition = "text[]"
)
private String[] sensorNames;

@Type( type = "int-array" )
@Column(
    name = "sensor_values", 
    columnDefinition = "integer[]"
)
private int[] sensorValues;</code>

Example

When inserting entities with array values, Hibernate will generate SQL statements similar to the following:

<code class="sql">INSERT INTO event (
    version, 
    sensor_names, 
    sensor_values, 
    id
) 
VALUES (
    0, 
    {&quot;Temperature&quot;,&quot;Pressure&quot;}, 
    {&quot;12&quot;,&quot;756&quot;}, 
    1
)</code>

The above is the detailed content of How to Map PostgreSQL Arrays to Java Arrays Using Hibernate?. 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