更新流程应该如何实施?是否建议对所有属性进行强制更新(第一个示例),或者我应该添加空检查条件以允许部分更新(第二个示例)?
第一个示例
@Transactional
@Override
public TeamDTO updateTeamById(Long id, TeamDTO teamDTO) throws ApiException {
Optional<Team> teamOptional = teamRepository.findById(id);
if (teamOptional.isPresent()) {
Team existingTeam = teamOptional.get();
// If objects ID are sent in JSON, set attributes via ID.
if (teamDTO != null) {
if(teamDTO.getCity() != null){
if (teamDTO.getCity().getId() != null) {
CityDTO cityDTO = cityServiceImp.getCityById(teamDTO.getCity().getId());
existingTeam.setCity(cityMapper.cityDTOToCity(cityDTO));
} else if(teamDTO.getCity().getName() != null){
existingTeam.setCity(cityMapper.cityDTOToCity(cityServiceImp.createCity(teamDTO.getCity())));
}
}
if(teamDTO.getStadium() != null){
if (teamDTO.getStadium().getId() != null) {
StadiumDTO stadiumDTO = stadiumServiceImp.getStadiumById(teamDTO.getStadium().getId());
existingTeam.setStadium(stadiumMapper.stadiumDTOToStadium(stadiumDTO));
} else if(teamDTO.getStadium().getName() != null){
existingTeam.setStadium(stadiumMapper.stadiumDTOToStadium(stadiumServiceImp.createStadium(teamDTO.getStadium())));
}
}
if(teamDTO.getDivision() != null){
if (teamDTO.getDivision().getId() != null) {
DivisionDTO divisionDTO = divisionServiceImp.getDivisionById(teamDTO.getDivision().getId());
existingTeam.setDivision(divisionMapper.divisionDTOToDivision(divisionDTO));
} else if(teamDTO.getDivision().getName() != null){
existingTeam.setDivision(divisionMapper.divisionDTOToDivision(divisionServiceImp.createDivision(teamDTO.getDivision())));
}
}
return teamMapper.teamToTeamDTO(teamRepository.save(existingTeam));
}
}
throw new TeamNotFoundException(id);
}
第二个例子
@Transactional
@Override
public TeamDTO updateTeamById(Long id, TeamDTO teamDTO) throws ApiException {
Team team = teamMapper.teamDTOToTeam(teamDTO);
Optional<Team> teamOptional = teamRepository.findById(id);
if (teamOptional.isPresent()) {
Team existingTeam = teamOptional.get();
existingTeam.setName(team.getName());
existingTeam.setDivision(team.getDivision());
existingTeam.setCity(team.getCity());
existingTeam.setStadium(team.getStadium());
existingTeam.setHomeMatches(team.getHomeMatches());
existingTeam.setAwayMatches(team.getAwayMatches());
return teamMapper.teamToTeamDTO(teamRepository.save(existingTeam));
}
throw new TeamNotFoundException(id);
}
这是一个 CRUD 个人项目。我对 POST 方法也有同样的疑问。
有了正确定义的类和关系,您可以简单地使用第二种方法,它干净且易于理解。
通过正确的关系定义,我的意思是类之间的映射(无论它们是一对一还是一对多等)和它们的CascadingType。在您的情况下,您可以使用CascadeType.ALL,它将父类上完成的所有 CRUD 操作传播到子类。因此,当您保存父对象时,您的子对象也会被保存。即使您的子类不存在于数据库中,它也会为您创建一个。
现在,您的第一种方法也适用于少数情况。例如,假设您正在发送带有一些城市数据的请求,其中对于给定的 ID,提供的名称与数据库中的名称不同。因此,对于您的方法,您不会更新数据库中的不同名称,而是从数据库中获取实际数据并进行设置。但如果您遵循第二种方法,它将覆盖城市名称的现有数据。