JPA Array Mapping

2019-06-21 18:29发布

How can I map an array of Doubles in JPA. I have the following code which fails because hibernate cannot initialise the array.

@Entity
public class YearlyTarget extends GenericModel {

    @Id
    public Integer  year;

    @ElementCollection
    public Double[] values;

    public YearlyTarget(int year) {
        this.year = year;
        this.values = new Double[12];
    }
}

3条回答
可以哭但决不认输i
2楼-- · 2019-06-21 18:48

JPA does not mandate being able to persist arrays to a separate table; obviously JDO does but then you have chosen not to use that. Consequently you need to either store them as @Lob, or change your java type to a List.

查看更多
神经病院院长
3楼-- · 2019-06-21 18:53

You don't specify the required database structure backing your mapping. @ElementCollection relies on a table that is joined up on retrieving the collection.

In Postgresql database for example you are able to store a simple array in within a column which is possible to map. You will need to in include a dependency:

<dependency>
    <groupId>com.vladmihalcea</groupId>
    <artifactId>hibernate-types-52</artifactId>
</dependency>

And your entity definition will look like:

@Entity
@Table(name = "products")
@TypeDefs(@TypeDef(name = "string-array", typeClass = StringArrayType.class))
public class Product {

    @Type(type = "string-array" )
    @Column(name = "colours")
    private String[] colours;

}

Currently the library only supports ints and strings, but it is a fairly simple task to add new types.

查看更多
地球回转人心会变
4楼-- · 2019-06-21 18:58

Use an Object type, such as ArrayList. Example

@ElementCollection
public ArrayList<Double> values;

public YearlyTarget(int year) {
    this.year = year;
    this.values = new ArrayList<Double>(12);
}
查看更多
登录 后发表回答