当前位置: 首页 > 知识库问答 >
问题:

组织。冬眠TransientPropertyValueException:对象引用未保存的临时实例-在刷新之前保存临时实例

公孙涵育
2023-03-14

我在我的项目中使用Spring引导和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
 }

增加任务的方法:

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对象上面给出了一个错误:

{"出发":"fff","到达":"ffff","isFreeWayEnable": false,"车站":[{"id": 1},{"id": 2}]}

共有1个答案

司徒耀
2023-03-14

移动是不持久的,你需要要么保存它,要么在Station中级联它,而且你有一个双向关系,这意味着关系的每个部分都应该引用另一个部分,所以在你的任务类中初始化站点列表

@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;
}
 类似资料: