I have a model that I want to persist using JPA 2 and this models contains a List of strings. On db, instead of the string list, i want to have a joined string with delimiter. Do i have to use an attribute containing the joined string or is a method "getJoindString" decorated with @Column enough?
This is an example:
@Entity
@Table(name = "times")
public class TimesList {
private transient List<String> times;
@Transient
public List<String> getTimes() {
if (times == null) {
times = new ArrayList<String>();
}
return times;
}
@Column(name = "joinedTimes")
public String getJoinedTimes() {
return String.join("|", getTimes());
}
public void setJoinedTimes(String joinedTimes) {
times = Arrays.asList(joinedTimes.split("|"));
}
}
Would this be a valid POJO for JPA 2 even if joinedTimes isn't actually a class attribute but only a value returned with a method?
that won't work... use this approach:
Leave your method getTime as transient, but create a field Annotated with @Column
... this field will map to the column that stores the times as joined string...
Create a package method and annotate with @PrePersist
... let's call it joinTime... this method will be called by JPA just before saving the entity into the database and will set the value of the time column as a joined string...
Create another package method and annotate with @PostLoad
... let's call it parseJoinTime... this method will be called by JPA just when the entity is load into the entityManager... in here you will transform your column value (the joined String) into your time list...
That's all...
If you want more info about this approach, lookup for JPA entity listeners