org.hibernate.TransientPropertyValueException:object引用未保存的瞬态实例 - 在刷新之前保存瞬态实例

时间:2017-08-14 16:05:43

标签: java spring spring-data

我在项目中使用spring boot和spring数据,我有两个类:

class Mission implements Serializable { private static final long 
serialVersionUID = 1L;
@Id
@GeneratedValue( strategy = GenerationType.IDENTITY )
private Long              id;
private String            departure;
private String            arrival;
private Boolean           isFreeWayEnabled;
@OneToMany( mappedBy = "mission" )
private List<Station>     stations;
// getters and setters
}

,第二堂课是:

@Entity
public class Station implements Serializable {

private static final long serialVersionUID = 1L;

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

@ManyToOne( fetch = FetchType.LAZY )
@JsonBackReference
private Mission           mission;
 //getters and setters
 }

添加任务的Methode:

public Mission addMision( Mission mission ) {
    // TODO Auto-generated method stub
    // Mission mission = getMissionById( mission.getId() );
    for ( Station station : mission.getStations() ) {
        station.setMission( mission );
        stationRepository.save( station );
    }
    return missionRepository.save( mission );
}

当我试图添加一个新任务时,它会给出上面的错误Json Object:

  

{&#34;离开&#34;:&#34; FFF&#34;&#34;到达&#34;:&#34; FFFF&#34;&#34; isFreeWayEnabled&#34;:假&#34;站&#34;:[{&#34; ID&#34;:1},{&#34; ID&#34;:2}]}

1 个答案:

答案 0 :(得分:1)

消息不是持久的,你需要保存它或者在Station中级联它,你也有一个双向关系,这意味着关系的每个部分都应该引用另一个部分 所以在你的Mission类中初始化电台列表

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

在电台中添加级联

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

然后在你的添加逻辑中,将关系的每个部分的引用放到另一个

public Mission addMision( Mission mission ) {

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