是否可以使用 Spring Data JPA 仅更新数据库中的某些列?
有一个实体类
@Entity
@NoArgsConstructor
@Setter
@EqualsAndHashCode
public class Task
{
private Long id;
private String title;
private Integer completed;
private Date date;
private Priority priority;
private Category category;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
public Long getId()
{
return id;
}
@Basic
@Column(name = "title")
public String getTitle()
{
return title;
}
@Basic
@Column(name = "completed")
public Integer getCompleted()
{
return completed;
}
@Basic
@Column(name = "date")
public Date getDate()
{
return date;
}
@ManyToOne
@JoinColumn(name = "priority_id", referencedColumnName = "id")
public Priority getPriority()
{
return priority;
}
@ManyToOne
@JoinColumn(name = "category_id", referencedColumnName = "id")
public Category getCategory()
{
return category;
}
}
控制器类
@RestController
@RequestMapping("/task")
public class TaskController
{
private TaskRepository taskRepository;
public TaskController(TaskRepository taskRepository)
{
this.taskRepository = taskRepository;
}
//Some CRUD methods
@PutMapping("/update")
public ResponseEntity update(@RequestBody Task task)
{
taskRepository.save(task);
return ResponseEntity.ok("Update was successful");
}
}
仓库接口
public interface TaskRepository extends JpaRepository<Task, Long>
{
}
当我从客户端发送 JSON 更新请求而不使用所有字段时,例如:
{
"id": 5,
"title": "Read the book"
}
所有那些我没有使用的字段都会自动设置为空,并且数据库中的所有列都被空覆盖。
有没有办法只更新那些我在 JSON 请求中直接指定字段值的列而不更改其余列?同时可以给JSON请求中的一些变量赋值为null,例如
{
"id": 5,
"title": "Read the book",
"completed": null
}