Saturday, July 23, 2016

Add customer behaviour to all spring data Jpa repositories in CDI context

Leave a Comment

Am successfully injecting jpa repositories using CDI. I wanted to add custom behaviour(soft deletes) to all repositories. When using spring I can enable customer behaviour by specifying the repository base class

@EnableJpaRepositories(repositoryBaseClass = StagedRepositoryImpl.class) 

How do I specify the same in CDI? Thanks in advance.

2 Answers

Answers 1

Here is the way to add custom logic to your repositories:

http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.custom-implementations

Basically you create a custom repository named {YourRepositoryName}Custom

interface UserRepositoryCustom {   public void someCustomMethod(User user); } 

And implement it:

class UserRepositoryImpl implements UserRepositoryCustom {    public void someCustomMethod(User user) {     // Your custom implementation   } } 

Your main repository should extend the custom one. Hope this helps!

Answers 2

To add custom behaviour to Jpa Repositories(in your case for delete),

1. Create a base repository like below:

@NoRepositoryBean public interface BaseRepository<T, ID extends Serializable> extends JpaRepository<T, ID> {      @Override     default void delete(T entity){         // your implementation     } } 

2. Now inherit Jpa Repositories from custom repository(i.e BaseRepository) like below:

public interface EmployeeRepository extends BaseRepository<Employee, Long> { } 

3. Inject your repository into Service class and call the delete method.

@Service class EmployeeService {      @Inject     private EmployeeRepository employeeRepository;      public void delete(Long id) {         employeeRepository.delete(id);     } } 

Now whenever you call delete on repositories which are child of BaseRepository, your custom implementation for delete will be invoked.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment