0 day streak
java / expert
Snippet

Customizing Global Repository Logic with SimpleJpaRepository

By extending SimpleJpaRepository and configuring it via @EnableJpaRepositories, you can add custom methods like refresh() to every repository instance in your application automatically.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
public class BaseRepositoryImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> {
private final EntityManager entityManager;
public BaseRepositoryImpl(JpaEntityInformation<T, ?> entityInformation, EntityManager entityManager) {
super(entityInformation, entityManager);
this.entityManager = entityManager;
}
@Transactional
public void refresh(T entity) {
entityManager.refresh(entity);
}
}
spring
Breakdown
1
extends SimpleJpaRepository<T, ID>
Inherits default Spring Data JPA implementation.
2
public void refresh(T entity)
Adds a custom 'refresh' method to synchronize entity state with the database.
3
entityManager.refresh(entity)
Direct use of EntityManager for low-level persistence operations.