Morteza Malvandi
Morteza Malvandi

Reputation: 1724

How prevent update automatically in Spring Data JPA?

I have a JPA entity as follow:

@Entity
@DynamicUpdate
@TypeDef(name = "json_binary", typeClass = JsonBinaryType::class)
public class Workflow {
   private Long id;
   private String name;

   @Type(type = "json_binary")
   @Column(columnDefinition = "jsonb")
   private List<AccessModel> users;
}

public class AccessModle {
   private String name;
   private Int permission;
}

And the repository:

@Repository
public interface WorkflowRepository extends JpaRepository<Workflow, Long> {}

Now when I just want to find a workflow(repository.findById(1)), The hibernate log is as follow:

Hibernate: select workflow0_.id as id1_12_0_, workflow0_.name as name2_12_0_, 
           workflow0_.users as users3_12_0_ where workflow0_.id=?
Hibernate: update workflow set users=? where id=?

I didn't modify users, But Hibernate set it. How can I prevent automatically update entity?

Update:

@Service
@Transactional
public class WorkflowServiceImpl {

    @Autowired
    private WorkflowRepository repository;

    public Workflow find(Long id) {
        return repository.findById(id);
    }
}

Upvotes: 2

Views: 2877

Answers (2)

SSK
SSK

Reputation: 3766

You have added @Transactional at service level so, it will be applicable for each method present in the service class. You need to add @Transactional(readOnly = true) on your find(Long id) method. It will solve your problem.

@Service
@Transactional
public class WorkflowServiceImpl {

    @Autowired
    private WorkflowRepository repository;

    @Transactional(readOnly = true)
    public Workflow find(Long id) {
        return repository.findById(id);
    }
}

It is best practice to add the @Transactional on required methods only instead at the class level.

Upvotes: 2

Ameya Pandilwar
Ameya Pandilwar

Reputation: 2778

You can include the following properties (insertable = false, updatable = false) along with the definition for @Column --

@Column(columnDefinition = "jsonb", insertable = false, updatable = false)

This will prevent from inserting or updating the value for the users

Upvotes: 1

Related Questions