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];
}
}
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.
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).
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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With