CodexBloom - Programming Q&A Platform

Hibernate not flushing changes to the database in a multi-threaded environment using Spring Boot

๐Ÿ‘€ Views: 1177 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-17
hibernate spring-boot multithreading Java

I'm having trouble with I tried several approaches but none seem to work. I'm currently working with an scenario with Hibernate where changes made to the database are not being flushed properly in a multi-threaded environment with Spring Boot. I'm using Hibernate 5.4.32.Final along with Spring Boot 2.5.4. The question arises when multiple threads attempt to continue data simultaneously. I have set up a service class where I am using `@Transactional` to handle the database operations. However, it seems that updates made in one thread are not visible to another thread until the application is restarted or until I manually call `entityManager.flush()`. Hereโ€™s a simplified version of my code: ```java @Service public class UserService { @Autowired private UserRepository userRepository; @Autowired private EntityManager entityManager; @Transactional public void updateUser(Long id, String newName) { User user = userRepository.findById(id).orElseThrow(() -> new EntityNotFoundException("User not found")); user.setName(newName); // Intentionally not calling entityManager.flush(); } } ``` In my controller, I have a method that concurrently updates the user from different threads: ```java @RestController @RequestMapping("/users") public class UserController { @Autowired private UserService userService; @PostMapping("/update") public ResponseEntity<Void> updateUser(@RequestParam Long id, @RequestParam String newName) { CompletableFuture.runAsync(() -> userService.updateUser(id, newName)); return ResponseEntity.ok().build(); } } ``` After executing updates, I found that if one thread updates the user, the other thread doesnโ€™t see the updated name unless I call `flush()`. Iโ€™ve tried checking the transaction isolation level in my application properties, which is set to `spring.jpa.properties.hibernate.connection.isolation=2` (READ_COMMITTED), but the scenario continues. Am I missing something in my configuration or usage patterns? Any insights would be greatly appreciated! This is part of a larger CLI tool I'm building. Has anyone else encountered this? This is happening in both development and production on Windows 10. Thanks for any help you can provide! I'm coming from a different tech stack and learning Java. I appreciate any insights!