Enable Hibernate second-level cache for better performance
Problem Context
Database is under heavy load. A developer enabled Hibernate's second-level cache on frequently accessed entities to reduce database hits. The application runs on multiple servers behind a load balancer.
Expert
300 points
File Changes (3)
src/main/java/com/example/entity/Product.java
MODIFIED
@@ -1 +1 @@
| 1 | 1 | @Entity |
| 2 | 2 | @Table(name = "products") |
| 3 | +@Cacheable |
|
| 4 | +@Cache(usage = CacheConcurrencyStrategy.READ_WRITE) |
|
| 3 | 5 | public class Product { |
| 4 | 6 | @Id |
| 5 | 7 | private Long id; |
| 6 | 8 | private String name; |
| 7 | 9 | private BigDecimal price; // Updated frequently by pricing engine |
| 8 | 10 | private Integer stock; // Updated on every purchase |
| 9 | 11 | } |
src/main/java/com/example/entity/User.java
MODIFIED
@@ -1 +1 @@
| 1 | 1 | @Entity |
| 2 | 2 | @Table(name = "users") |
| 3 | +@Cacheable |
|
| 4 | +@Cache(usage = CacheConcurrencyStrategy.READ_WRITE) |
|
| 3 | 5 | public class User { |
| 4 | 6 | @Id |
| 5 | 7 | private Long id; |
| 6 | 8 | private String email; |
| 7 | 9 | private String name; |
| 8 | 10 | } |
src/main/resources/application.properties
MODIFIED
@@ -10 +10 @@
| 10 | 10 | # Database Configuration |
| 11 | 11 | spring.datasource.url=jdbc:postgresql://localhost:5432/myapp |
| 12 | + |
|
| 13 | +# Enable Hibernate second-level cache |
|
| 14 | +spring.jpa.properties.hibernate.cache.use_second_level_cache=true |
|
| 15 | +spring.jpa.properties.hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory |
|
| 12 | 16 | |
Login Required: You must be registered to submit reviews and receive AI feedback.
Register or
login to start reviewing!
Your Review
Review Tips
- Look for security vulnerabilities (SQL injection, XSS, etc.)
- Check for null pointer exceptions and error handling
- Consider performance implications
- Evaluate code maintainability and readability
- Check for proper resource management
- Look for logic errors or edge cases