"After years of ignoring some key JPA methods and annotations, I finally explored them - and what happened next was shocking: my application became up to 10× faster with fewer queries, less memory use, and way cleaner code. š If you are not a Medium Member then Click hereto read free. š 1. JpaRepository.existsById() Instead of findById() If you only need to check if something exists: if (userRepository.existsById(id)) { // no need to load entire entity} ā Why it's faster: Avoids unnecessary entity loading and reduces SQL size."
"š¾2. saveAll() - The Implicit Batch Saver For years, I called save() in a loop - like this: for (User user : users) { userRepository.save(user);} But that's inefficient. Instead, use: userRepository.saveAll(users); Hint: saveAll() still calls save() for each entity internally, but the persistence context can optimize batching if you configure it correctly (e.g., using hibernate.jdbc.batch_size)."
Using existsById() avoids loading full entities when only existence needs checking, which reduces SQL size and memory usage. Replacing repeated save() calls with saveAll() enables the persistence context to optimize operations and allows JDBC batching when hibernate.jdbc.batch_size is configured. saveAll() still delegates to save() per entity, so correct batching configuration is necessary for best results. These method choices cut query counts, lower memory consumption, and simplify repository code. Applied correctly, they can produce substantial performance improvements, sometimes achieving up to tenfold speed gains.
Read at Medium
Unable to calculate read time
Collection
[
|
...
]