不使用SpringJPA更新实体中未指定的字段

pbpqsu0x  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(349)

我正在用restapi创建一个应用程序,因此其中一个端点要创建,另一个要更新。当我尝试更新实体时,我的问题出现了,它更新了我在创建中添加的字段,但没有更新。我在试着 @DynamicUpdate 以及 @SelectBeforeUpdate 它仍然遵循同样的行为。
控制器

@RestController
@RequestMapping("/v01")
@Slf4j
public class ProjectController {

@Autowired
private ProjectServiceIface projectService;

@PostMapping(path = "/project", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Project> createProject(@Valid @RequestBody Project project, BindingResult result){
    if(result.hasErrors()){
        throw new BusinessServiceException(result.getFieldError().getDefaultMessage(), result.getFieldError().getField() + " " + result.getFieldError().getCode());
    }
    Project projectSaved = projectService.createProject(project);
    HttpHeaders headers = new HttpHeaders();
    headers.add("Location", projectSaved.getId().toString());

    return new ResponseEntity<>(project, headers, HttpStatus.CREATED);
}

@PatchMapping(path = "/project", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Project> updateProject(@Valid @RequestBody Project project, BindingResult result){
    if(result.hasErrors()){
        throw new BusinessServiceException(result.getFieldError().getDefaultMessage(), result.getFieldError().getField() + " " + result.getFieldError().getCode());
    }
    Project projectUpdated = projectService.updateProject(project);

    if(projectUpdated == null) {
        return new ResponseEntity<>(null, new HttpHeaders(), HttpStatus.NOT_FOUND);
    }
    HttpHeaders headers = new HttpHeaders();
    headers.add("Location", projectUpdated.getId().toString());

    return new ResponseEntity<>(projectUpdated, headers, HttpStatus.CREATED);
}
}

服务

@Service
public class ProjectServiceImpl implements ProjectServiceIface {

@Autowired
private ProjectRepository projectRepository;

@Autowired
private ProjectRepository projectRepository;

@Override
public Project createProject(Project project) {
    Project projectFound = projectRepository.findByName(project.getName());
    if(projectFound != null){
        throw new BusinessServiceException(Constants.FUNCTIONAL_ERROR, "The Project already exists");
    }
    project.setCreateTime(new Date());

    Project projectSaved = projectRepository.save(project);
    return projectSaved;
}

@Override
public Project findProjectById(String id) {
    Project projectFound = null;
    if(!StringUtils.isNumeric(id)){
        throw new BusinessServiceException(Constants.FUNCTIONAL_ERROR, "The ID is not in a correct format");
    }
    Optional<Project> projectOptional = projectRepository.findById(Integer.valueOf(id));
    if(projectOptional.isPresent()){
        projectFound = projectOptional.get();
    }
    return projectFound;
}

@Override
public Project updateProject(Project project) {
    Project projectUpdated = null;
    Optional<Project> projectFound = projectRepository.findById(project.getId());
    if(projectFound.isPresent()){
        project.setUpdateTime(new Date());
        //Project projectMapped = EntityMapper.projectMapper(project);
        projectUpdated = projectRepository.save(project);
    }
    return projectUpdated;
}

@Override
public Project findProjectByName(String projectName) {
    Project project = projectRepository.findByName(projectName);

    return project;
}
}

存储库

public interface ProjectRepository extends CrudRepository<Project, Integer> {

@Query(value = "SELECT * FROM project p WHERE p.name = :projectName", nativeQuery = true)
Project findByName(String projectName);

 }

项目(实体)

@Entity
@Data
@DynamicUpdate
@SelectBeforeUpdate
@Table(name = "project")
public class Project implements Serializable {
private static final long serialVersionUID = -6163778458602900643L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@NotEmpty
private String name;
@NotEmpty
private String tag;
private String icon;
@Column(name = "create_user", updatable = false)
private String createUser;
@Column(name = "update_user")
private String updateUser;
@Column(name = "create_time", updatable = false)
private Date createTime;
@Column(name = "update_time")
private Date updateTime;
}

这是我用于创建的请求:

{
"name" : "Test12",
"tag" : "TST",
"icon" : "/var/usr"
}

我得到的答复是:

{
"id": 5,
"name": "Test12",
"tag": "TST",
"icon": "/var/usr",
"createUser": null,
"updateUser": null,
"createTime": "2020-01-24T22:33:48.499+0000",
"updateTime": null
}

这是我执行的更新请求:

{
"id": 5,
"name": "Test5",
"tag": "AAA"
}

我得到的答复是:

{
"id": 5,
"name": "Test67",
"tag": "AAA",
"icon": null,
"createUser": null,
"updateUser": null,
"createTime": null,
"updateTime": "2020-01-24T22:44:50.914+0000"
}

你们都能看到 icon 以及 createTime 已设置为空。我只想特别更新我在请求/实体中发送的字段。

s4n0splo

s4n0splo1#

如果您在实体类中共享要在创建时插入/更新的代码remove updateable=false,这会很有帮助
问题是您没有从数据库中获取项目的值。如果值存在,您正在签入db,但在项目json图标中保存以json发送的值不存在
修正的方法是,你需要根据id获取值,然后再次设置要更改的值。这样,旧值将被检索,新值将被更新

xxe27gdn

xxe27gdn2#

您可以使用spring数据块方法,或者显式地调用entitymanager上的merge

相关问题