Home > Java > javaTutorial > body text

How to Map PostgreSQL Arrays to Java Arrays Using Hibernate?

Linda Hamilton
Release: 2024-10-25 00:31:02
Original
449 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!