使用弹簧数据jpa更新单个字段 [英] Update single field using spring data jpa
问题描述
我正在使用spring-data的存储库 - 非常方便,但我遇到了一个问题。我可以轻松更新整个实体,但我认为只需要更新一个字段就没有意义了:
I'm using spring-data's repositories - very convenient thing but I faced an issue. I easily can update whole entity but I believe it's pointless when I need to update only a single field:
@Entity
@Table(schema = "processors", name = "ear_attachment")
public class EARAttachment {
private Long id;
private String originalName;
private String uniqueName;//yyyy-mm-dd-GUID-originalName
private long size;
private EARAttachmentStatus status;
更新我只是调用方法保存。在日志中我看到了跟随:
to update I just call method save. In log I see the followwing:
batching 1 statements: 1: update processors.ear_attachment set message_id=100,
original_name='40022530424.dat',
size=506,
status=2,
unique_name='2014-12-16-8cf74a74-e7f3-40d8-a1fb-393c2a806847-40022530424.dat'
where id=1
我希望看到这样的事情:
I would like to see some thing like this:
batching 1 statements: 1: update processors.ear_attachment set status=2 where id=1
Spring的存储库有很多工具可以使用名称约定来选择一些东西,也许有更新类似updateForStatus(int status);
Spring's repositories have a lot of facilities to select something using name conventions, maybe there is something similar for update like updateForStatus(int status);
推荐答案
你可以尝试这样的事情:
You can try something like this:
@Modifying
@Query("update EARAttachment ear set ear.status = ?1 where ear.id = ?2")
int setStatusForEARAttachment(Integer status, Long id);
您还可以使用命名参数,如下所示:
You can also use named params, like this:
@Modifying
@Query("update EARAttachment ear set ear.status = :status where ear.id = :id")
int setStatusForEARAttachment(@Param("status") Integer status, @Param("id") Long id);
int返回值是更新的行数。您也可以使用 void
return。
The int return value is the number of rows that where updated. You may also use void
return.
在参考文档。
这篇关于使用弹簧数据jpa更新单个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!