嘗試使用Hibernate 將數字組查詢資料庫導致數字組數組期間出現異常。
要解決此問題,請按照以下步驟操作:
<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中文網其他相關文章!