Java Spring Boot Rest:如何将另一个对象作为属性来传递另一个保存对象



我正在尝试保存一个对象Rating,该对象有另一个Mobile,因此它包括一个等级和一个电话。

这是移动实体:

@Entity
@NoArgsConstructor
@AllArgsConstructor
@Data
public class Mobile {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private double price;
}

这是评级实体

@Entity
@NoArgsConstructor
@AllArgsConstructor
@Data
public class Rating {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
private Mobile mobile;
private int grade;
}

RatingService类中的方法saveRating

public Rating saveRating(Rating rating) {
Rating theRating = new Rating();
Mobile theMobile = mobileRepo.getById(rating.getMobile().getId());
theRating.setGrade(rating.getGrade());
theRating.setMobile(theMobile);
return ratingRepo.save(theRating);
}

以及在休息控制器中节省的方法

@Autowired
private RatingService ratingService;
@RequestMapping(value = "/rating", method = RequestMethod.POST)
public Rating newRating(@RequestBody Rating rating){
return ratingService.saveRating(rating);
}

我有所有的@Service@RestController@Autowired注释。其他功能包括保存手机、删除手机和查看手机,甚至查看我手动添加到数据库中的评分。我尝试过在控制器和RatingService中改变新的rating方法,它只获取移动id和等级,然后通过mobileRepository找到移动设备,并将其保存为移动设备进行评级,但我在这方面没有取得进展,所以我从我开始的时候就回到了这个方法。这样做似乎很简单,但目前并非如此。以下是邮递员的结果:这是来自的邮递员

当前,您正在尝试映射值"移动"=1;评级"=4到具有字段"0"的实例;id""移动";(不是整数(和";等级";,因此,您收到了Bad Request的响应,因为提供的JSON与指定的(@RequestBody(Java类型不匹配。

不使用实体作为DataTransferObjects,您可以向引入以下dto

@Data
public class RatingDto {
private int mobileId;
private int grade;
}

然后,您的请求还应该在名称为mobileId的字段中包含移动设备的id,以匹配dto。

您的控制器端点看起来是这样的:

private Rating tryMap(RatingDto dto) {
var mobileId = dto.getMobileId();
var mobile = mobileRepo.findById(mobileId)
.orElseThrow(() -> 
new IllegalArgumentException("Mobile with id " + mobileId + "could not be found.");
var rating = new Rating();
rating.setGrade(dto.getGrade);
rating.setMobile(mobile);
return rating;
}
@PostMapping(value = "/rating")
public Rating newRating(@RequestBody RatingDto dto) {
var rating = tryMap(dto);
return ratingService.saveRating(rating);
}

最新更新