Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA: The redundant save anti-pattern

So I have this method:

@Transactional
public void savePostTitle(Long postId, String title) {
    Post post = postRepository.findOne(postId);
    post.setTitle(title);
}

As per this post:

The save method serves no purpose. Even if we remove it, Hibernate will still issue the UPDATE statement since the entity is managed and any state change is propagated as long as the currently running EntityManager is open.

and indeed the update statement is issued, but if I run the method without the @Transactional annotation:

public void savePostTitle(Long postId, String title) {
        Post post = postRepository.findOne(postId);
        post.setTitle(title);
    }

Hibernate will not issue the update statement so one has to call postRepository.save(post);explicitly.

What is the difference between using @Transactional or not in this specific scenario?

like image 635
rena Avatar asked Nov 01 '18 17:11

rena


1 Answers

In a standard configuration, the scope of a persistence context is bound to the transaction.

If you don't have an explicit transaction defined by means of the annotation your (non-existing) transaction span just the reading call to the database. After that the entity just loaded is not managed. This means changes to it won't get tracked nor saved. Flushing won't help because there are no changes tracked.

like image 189
Jens Schauder Avatar answered Sep 28 '22 02:09

Jens Schauder