我遇到了一个问题,即我的JPA @ElementCollection表中没有任何持久化的东西。 From what I can tell,我想我了解@ElementCollection的基本概念。我的猜测是出问题的原因是因为我在ElementCollection对象中有一个Embeddable

一个简单的例子:

@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;
    }
    ...
}


关于可能出什么问题的任何线索?



编辑:附加信息

为了简洁起见,我将尽量使其他信息尽可能简短。

创建计算原因

public static CalculationReason create(List<String> descriptions) {
    return new CalculationReason(descriptions);
}


创建计算历史

public static CalculationHistory create(CalculationReason calculationReason) {
    CalculationHistory history = new CalculationHistory();
    history.setCalculationReason(calculationReason);
    ...
    return history;
}


在CalculationHistory#create上的调试信息

java - Embeddable中的JPA ElementCollection不持久-LMLPHP

Hibernate DAO存储库

@Override
public <S extends E> S save(S entity) {
    return getHibernateTemplate().merge(getEntityClass().getName(), entity);
}


Hibernate生成的SQL

Hibernate: insert into calculation_history (created_date, modified_date, modified_by, reason, system) values (?, ?, ?, ?, ?)


看起来Hibernate甚至都没有生成我期望的insert into calculation_description... SQL(忽略多余的字段)

最佳答案

经过数小时的反复试验,我能够通过初始化descriptions字段来解决问题:

 private List<String> descriptions = Lists.newArrayList();


老实说,我不太确定为什么这会有所作为,因此欢迎任何外界意见。

10-06 12:59