I am making an application in spring boot. It was working fine until I made it asynchronous. I am not getting any error and no json response. I cannot figuring it out. How can i solve this. Please help me in figuring it out.
Post Repository:
@Repository
public interface PostRepository extends JpaRepository<Post,Long> {
@Async
Post findBySubject(String subject);
}
Post Service:
@Service
@Transactional
public class PostService {
@Autowired
private PostRepository postRepository;
@Async
public CompletableFuture<Post> find(String subject) throws ExecutionException,
InterruptedException {
System.out.println("Current Thread Name: " Thread.currentThread().getName());
Post post = postRepository.findBySubject(subject);
System.out.println("Current Thread Name: " Thread.currentThread().getName());
return CompletableFuture.completedFuture(post);
}
}
Post Controller:
@Slf4j
@RestController
@RequestMapping("/posts")
public class PostController {
@Autowired
private PostService postService;
@GetMapping
public CompletableFuture<Post> get(@RequestParam String subject){
try {
System.out.println("Current Thread Name: " Thread.currentThread().getName());
return postService.find(subject);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
}
CodePudding user response:
Jpa Repository is not Async
@Async Post findBySubject(String subject); }
This is causing problem.
If you want it to work then you need to return CompletableFuture instead. Here I am referring a link from stack overflow : https://stackoverflow.com/a/38421923/11928455 (But again this is not recommanded)
So, remove @Async from repository. JpaRepository will not work asynchronously. If you need async repo then look into spring reactive repositories instead.