Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA Array Mapping

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];
    }
}
like image 613
emt14 Avatar asked Jan 16 '12 06:01

emt14


People also ask

What is JPA mapping?

The One-To-One mapping represents a single-valued association where an instance of one entity is associated with an instance of another entity. In this type of association one instance of source entity can be mapped atmost one instance of target entity.

What is @ElementCollection in JPA?

JPA 2.0 defines an ElementCollection mapping. It is meant to handle several non-standard relationship mappings. An ElementCollection can be used to define a one-to-many relationship to an Embeddable object, or a Basic value (such as a collection of String s).

What is JPA Baeldung?

The Java Persistence API (JPA) is a specification that defines how to persist data in Java applications. The primary focus of JPA is the ORM layer. Hibernate is one of the most popular Java ORM frameworks in use today.


2 Answers

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.

like image 131
Tian Na Avatar answered Oct 01 '22 18:10

Tian Na


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);
}
like image 30
Codemwnci Avatar answered Oct 01 '22 16:10

Codemwnci