2

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); } } 
4
  • 1
    Can you add the service method which calls repository.findById(1)? Commented Aug 9, 2020 at 10:14
  • 2
    Define equals and hashcode in AccessModle so that jpa can verify fields not updated Commented Aug 9, 2020 at 20:12
  • Can you show us your controller or Service impl which has the method call? Commented Aug 10, 2020 at 3:05
  • It shouldn't issue update at all with the code you have shown us. Who is calling workflowService. find and what they are doing with the result and does that method have @Transactional too? Commented Aug 10, 2020 at 10:54

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.