Home >Java >javaTutorial >How to Map PostgreSQL Arrays to Java Arrays 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:
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>
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>
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>
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, {"Temperature","Pressure"}, {"12","756"}, 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!