尝试使用 Hibernate 将数字 PostgreSQL 数组映射到数字 Java 数组会导致数据库查询期间出现异常。
要解决此问题,请按照以下步骤操作:
<code class="xml"><dependency> <groupId>com.vladmihalcea</groupId> <artifactId>hibernate-types-52</artifactId> <version>${hibernate-types.version}</version> </dependency></code>
在 Java 类中,指定将用于映射的自定义 Hibernate 类型数组:
<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>
StringArrayType 和 IntArrayType 类不是内置的;您需要按如下方式创建它们:
<code class="java">@TypeDef( name = "string-array", typeClass = StringArrayType.class ) @TypeDef( name = "int-array", typeClass = IntArrayType.class )</code>
当持久化具有数组值的实体时,Hibernate 将生成以下 SQL 语句:正确映射数组。
假设以下表结构:
<code class="sql">CREATE TABLE event ( id int8 not null, version int4, sensor_names text[], sensor_values integer[], primary key (id) );</code>
您可以将其映射到以下 Java 类:
<code class="java">@Entity(name = "Event") @Table(name = "event") public static class Event extends BaseEntity { @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; //Getters and setters omitted for brevity }</code>
当插入具有数组值的实体时,Hibernate 将生成如下 SQL 语句:
<code class="sql">INSERT INTO event ( version, sensor_names, sensor_values, id ) VALUES ( 0, {NULL}, {NULL}, 0 ); INSERT INTO event ( version, sensor_names, sensor_values, id ) VALUES ( 0, {"Temperature","Pressure"}, {"12","756"}, 1 );</code>
以上是如何使用 Hibernate 将 PostgreSQL 数组映射到 Java 数组?的详细内容。更多信息请关注PHP中文网其他相关文章!