Home >Java >javaTutorial >How to Map PostgreSQL Arrays to Java Arrays with Hibernate: A Guide to Numeric Array Mapping
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.
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, 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.
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>
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!