0

First of all, this is not a duplicate of Spring Data: Override save method. I want to override the save method, and I know where to find the documentation, but my question is how to call the original implementation in my custom code.

To override save() method in spring-data-*, you do something like below:

interface CustomizedSave<T> {
  <S extends T> S save(S entity);
}

class CustomizedSaveImpl<T> implements CustomizedSave<T> {

  public <S extends T> S save(S entity) {
    // Your custom implementation
  }
}

interface UserRepository extends CrudRepository<User, Long>, CustomizedSave<User> {
}

interface PersonRepository extends CrudRepository<Person, Long>, CustomizedSave<Person> {
}

My question is how to call the "super" implementation of save()? In spring-data-elasticsearch, the default save() implementation is not so simple to set up (basically I need to copy AbstractElasticsearchRepository source code), so I would rather not do this.

Mateusz Stefek
  • 3,478
  • 2
  • 23
  • 28
  • In the code shown in the question, where should `super.save(...)` be called? Has an attempt been made to call `super.save(...)`? If not, what prevents it; if yes, what problem is being faced? The question seems unclear in its current form. – manish Aug 10 '18 at 10:27

1 Answers1

1
@Autowired
private EntityManager em;

@Override
public User save(User entity) {
    JpaRepositoryFactory jrf = new JpaRepositoryFactory(em);
    UserRepositories repoWithoutCustom = jrf.getRepository(UserRepositories.class);
do somth....
}

Where repoWithoutCustom what you need, your UserRepository without any customized methods. Just use required RepositoryFactory, in your case Elastic as i understood

borino
  • 1,720
  • 1
  • 16
  • 24
  • Your answer is about spring-data-jpa. I’m more interested in a generic solution for all spring-data flavours. In JPA, you simply call EntityManager.save(), but in spring-data-elasticsearch, it doesn’t seem that simple. – Mateusz Stefek Aug 09 '18 at 19:46
  • Did you trying : just create `new ElasticsearchRepositoryFactory(template)` (template is `ElasticsearchTemplate`) and getting required repository? – borino Aug 10 '18 at 04:07