Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA ElementCollection within Embeddable not persisted

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?


Edit: Additional Information

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

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)

like image 914
Gian Paolo Buffo Avatar asked Jan 27 '23 14:01

Gian Paolo Buffo


1 Answers

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.

like image 114
Gian Paolo Buffo Avatar answered Jan 31 '23 20:01

Gian Paolo Buffo