保存父实体时,不会保存子实体。为什么?

时间:2018-11-15 07:35:35

标签: java spring

我有一个 FilterEvent类,如下所示

public class FilterEvent {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer filterId;
    @NotNull
    private String userId;
    @NotNull
    private String columnId;
    private String columnName;
    private String operator;
    private String filterValue;
    //@Column(columnDefinition = "varchar(255) DEFAULT 'filter'")
    @ColumnDefault("'frequency'")
    private String filterType;

    @JsonIgnore
    @ManyToOne(cascade = CascadeType.PERSIST,fetch = FetchType.EAGER)
    @JoinColumn(name = "dataset_id")
    private Dataset dataset;

    @JsonIgnore
    @ManyToOne(cascade = CascadeType.PERSIST,fetch = FetchType.EAGER)
    @JoinColumn(name = "prep_id")
    private Preparation preparation;
}

然后我将此类映射为带有 @ManyToOne

的Preparation类

我的筹备课如下所示

@Entity
@Table(name = "preparation")
public class Preparation {

    @Id
    @Column(name = "prep_id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long prepId;
    @Column(name = "prep_name")
    private String prepName;

    @OneToMany(mappedBy = "preparation", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private Set<FilterEvent> filterEvents;
}

当我在如下所示的保存准备期间尝试更新 filterEvents 时,filterEvents不会保存在 FilterEvent 表中。

public Preparation savePreparation(Integer datasetId, Preparation preparation) throws DatasetNotFoundException {
    LOGGER.trace("PreparationService : inside addPreparation");
    Dataset dataset = datasetRepository.findById(datasetId).get();
    if (null == dataset) {
        throw new DatasetNotFoundException(Integer.toString(datasetId));
    }
    preparation.setDataset(dataset);
    preparation.setUserId(dataset.getUserId());
    Set<FilterEvent> filterEvents = preparation.getFilterEvents();
    if(null!=filterEvents) {
        filterEvents.stream().forEach(f -> f.setFilterId(null));
    }

    preparationRepository.save(preparation);
    Long prepId = preparation.getPrepId();
    return preparationRepository.findById(prepId).get();

}

为什么会这样? 保存准备时,需要将 filterEvents 保存在 FilterTable 中。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

将FilterEvent类属性更改为级联类型ALL。正如您提到的PERSIST。

public class FilterEvent {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer filterId;
@NotNull
private String userId;
@NotNull
private String columnId;
private String columnName;
private String operator;
private String filterValue;
//@Column(columnDefinition = "varchar(255) DEFAULT 'filter'")
@ColumnDefault("'frequency'")
private String filterType;

@JsonIgnore
@ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
@JoinColumn(name = "dataset_id")
private Dataset dataset;

@JsonIgnore
@ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
@JoinColumn(name = "prep_id")
private Preparation preparation;}