如何使用spring数据同时持久化三个实体

时间:2018-03-12 20:11:10

标签: java hibernate spring-boot spring-data

嗨,伙计们,我想一次性地持续三个对象代码:

@Entity
public class Mission implements Serializable {
@Id
@GeneratedValue( strategy = GenerationType.IDENTITY )
private Long               id;

@OneToMany( mappedBy = "mission" )
@JsonManagedReference
private List<Station>      stations         = new ArrayList<>();

@OneToMany( mappedBy = "mission" )

@JsonManagedReference
private List<StationPrice> stationsPrice    = new ArrayList<>();
}
Station :
@Entity
 public class Station implements Serializable {



@Id
@GeneratedValue( strategy = GenerationType.IDENTITY )
private Long              id;
private String            station;

@ManyToOne( fetch = FetchType.LAZY, cascade = CascadeType.ALL )
@JsonBackReference
private Mission           mission;
}

StationPrice:

@Entity
public class StationPrice implements Serializable {

/**
 * 
 */


@Id
@GeneratedValue( strategy = GenerationType.IDENTITY )
private Long              Id;
private String            stationsName;
private String            stationsPrice;

@ManyToOne( fetch = FetchType.LAZY, cascade = CascadeType.ALL )
@JsonBackReference
private Mission           mission;
}

所以当我坚持他的时候,我使用了下面的方法:

@Override
public Mission addMision( Mission mission ) {

    List<Station> stations = mission.getStations();
    List<StationPrice> stationPrices = mission.getStationsPrice();

    mission.setStations( new ArrayList<Station>() );
    for ( Station station : stations ) {
        station.setMission( mission );
        mission.getStations().add( station );
        mission = stationRepository.save( station ).getMission();
    }
    return mission;

}

这个Methode只支持任务实体和站点实体而不是stationPrice实体,有没有办法一次性地持久化三个实体?

1 个答案:

答案 0 :(得分:0)

我想如果添加

@OneToMany(fetch = FetchType.LAZY, targetEntity=Station.class,  cascade = CascadeType.ALL )
@JsonManagedReference
private List<Station> stations = new ArrayList<>();

@OneToMany(fetch = FetchType.LAZY,  targetEntity=StationPrice.class, cascade = CascadeType.ALL )
@JsonManagedReference
private List<StationPrice> stationsPrice = new ArrayList<>();
}

然后你可以简单地坚持Mission Entity,这将持续站和站价格。

修改 顺便说一句,你的ERM看起来很奇怪,在代码中,你循环使用任务站,然后添加回到任务中?和stationPrice根本没用过?