I am running into an issue where nothing is being persisted into my JPA @ElementCollection
table. From what I can tell, I think I understand the basic idea of @ElementCollection
. My guess is that the reason something is going wrong is because I have an ElementCollection
within an Embeddable
Object.
A simple example:
@Entity
public class CalculationHistory {
private CalculationReason calculationReason;
@Embedded
public CalculationReason getCalculationReason() { return calculationReason; }
protected void setCalculationReason(CalculationReason calculationReason {
this.calculationReason = calculationReason;
}
...
}
@Embeddable
public class CalculationReason {
private List<String> descriptions;
@ElementCollection
@CollectionTable(name = "calculation_description", joinColumns = @JoinColumn("calculation_history_id"))
@Column(name = "description")
public List<String> getDescriptions() { return descriptions; }
public void setDescriptions(List<String> descriptions) {
this.descriptions = descriptions;
}
...
}
Any clues as to what could be going wrong?
For the sake of brevity, I'll try to keep the additional information as short as possible.
Creating CalculationReason
public static CalculationReason create(List<String> descriptions) {
return new CalculationReason(descriptions);
}
Creating CalculationHistory
public static CalculationHistory create(CalculationReason calculationReason) {
CalculationHistory history = new CalculationHistory();
history.setCalculationReason(calculationReason);
...
return history;
}
Debug Info at CalculationHistory#create
Hibernate DAO Repository
@Override
public <S extends E> S save(S entity) {
return getHibernateTemplate().merge(getEntityClass().getName(), entity);
}
Hibernate-generated SQL
Hibernate: insert into calculation_history (created_date, modified_date, modified_by, reason, system) values (?, ?, ?, ?, ?)
Looks like Hibernate is not even generating the insert into calculation_description...
SQL that I'm expecting (ignore the extra fields)
After many hours of trial-and-error, I was able to fix my problem by initialising the descriptions
field:
private List<String> descriptions = Lists.newArrayList();
Honestly I'm not too sure why this actually makes a difference so any outside opinions are welcome.
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