获取新插入数据的id
还有一个问题就是在service实现类我本来是这样写的,我想先插入航线信息,然后根据新增的航线信息,获取到新的id,然后根据航线id插入航线对应的点的数据。
Override
public int insertFlightPlansAndWaypoints(FlightPlans newflightPlans, List<Waypoints> waypoints) {
newflightPlans.setCreateTime(DateUtils.getNowDate());
FlightPlans newUploadflightPlans = flightPlansMapper.insertUploadFlightPlans(newflightPlans);
//获取航线id
String fpId = newUploadflightPlans.getFpId();
for (Waypoints waypoint : waypoints) {
waypoint.setWpFlightPlanId(fpId);
waypointsMapper.insertWaypoints(waypoint);
}
但一直报错,原因是flightPlansMapper.insertUploadFlightPlans(newflightPlans);返回的都是int类型的数字,是插入了几条数据。我这里用FlightPlans 实体类接收,就不行。
后来发现,插入后,可以直接获取id,
@Override
public int insertFlightPlansAndWaypoints(FlightPlans newflightPlans, List<Waypoints> waypoints) {
newflightPlans.setCreateTime(DateUtils.getNowDate());
// FlightPlans newUploadflightPlans = flightPlansMapper.insertUploadFlightPlans(newflightPlans);
int rows = flightPlansMapper.insertFlightPlans(newflightPlans);
//获取航线id
String fpId = newflightPlans.getFpId();
long wpIndex = 0;
for (Waypoints waypoint : waypoints) {
waypoint.setWpFlightPlanId(fpId);
waypoint.setWpIndex(wpIndex++); // 设置 wp_index,并在每次循环中加 1
waypointsService.insertWaypoints(waypoint);
}
return rows;
}
通过使用 @Options(useGeneratedKeys = true, keyProperty = "fpId")
注解,你可以在插入记录后获取数据库生成的主键值,并将其用于插入相关的 Waypoints
数据。这样,你就可以确保每个 Waypoints
对象正确地关联到对应的 FlightPlans
记录。