71

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's repositories have a lot of facilities to select something using name conventions, maybe there is something similar for update like updateForStatus(int status);

buræquete
  • 14,226
  • 4
  • 44
  • 89
Dmitrii Borovoi
  • 2,814
  • 9
  • 32
  • 50

3 Answers3

116

You can try something like this on your repository interface:

@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);

The int return value is the number of rows that where updated. You may also use void return.

See more in reference documentation.

Lubo
  • 1,621
  • 14
  • 33
Bruno Ribeiro
  • 5,956
  • 5
  • 39
  • 48
  • Thanks, work now, but I'm wondering if it is better than using entityManager.creatQuery(..)? I'm looking for something type safe – Dmitrii Borovoi Mar 23 '15 at 04:27
  • @DmitriiBorovoi This will also call `em.createQuery`, if I remember correctly, so is the samething. If you want something type safe, you will need a way to know which attributes were modified to build the query. After this, you can you use custom repository to execute the query (http://docs.spring.io/spring-data/data-jpa/docs/current/reference/html/#repositories.custom-implementations). – Bruno Ribeiro Mar 23 '15 at 10:00
33

Hibernate offers the @DynamicUpdate annotation. All we need to do is to add this annotation at the entity level:

@Entity(name = "EARAttachment ")
@Table(name = "EARAttachment ")
@DynamicUpdate
public class EARAttachment {
    //Code omitted for brevity
}

Now, when you use EARAttachment.setStatus(value) and executing "CrudRepository" save(S entity), it will update only the particular field. e.g. the following UPDATE statement is executed:

UPDATE EARAttachment 
SET    status = 12,
WHERE  id = 1
Vijai
  • 2,369
  • 3
  • 25
  • 32
  • 1
    Excuse me, and what will be the statement executed if I don't use @DynamicUpdate? Will it still process Update statement if I do save() after setter? – Andrey M. Stepanov Feb 21 '19 at 10:54
  • 2
    @AndreyM.Stepanov Yes, UPDATE SQL will be generated. And also note that `@DynamicUpdate` has some performance overhead as explained in https://www.baeldung.com/spring-data-jpa-dynamicupdate. Use only when the number of columns is large. – The Coder Sep 06 '19 at 03:37
  • 3
    The biggest draw back of this approach is that you need to select and bind the entity first before it's value can be updated. Correct? – Andrew T Finnell Apr 30 '20 at 20:21
-7

You can update use databind to map @PathVariable T entity and @RequestBody Map body. And them update body -> entity.

public static void applyChanges(Object entity, Map<String, Object> map, String[] ignoreFields) {
    map.forEach((key, value) -> {
        if(!Arrays.asList(ignoreFields).contains(key)) {
            try {
                Method getMethod = entity.getClass().getMethod(getMethodNameByPrefix("get", key));
                Method setMethod = entity.getClass().getMethod(getMethodNameByPrefix("set", key), getMethod.getReturnType());
                setMethod.invoke(entity, value);
            } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    });
}