0

Is it possible to write my own function implementation along usage of spring repositories?

I would like to actually implement the function

getUserByFirstName() 

and not get it automagically. While i still want to get

getUserById()

automagically from spring-data.

1) is it possible?

2) is it possible to achieve logging for all methods spring data automagically generates? (or should i write them manually with

logger.log("entering method ...");
Urbanleg
  • 6,252
  • 16
  • 76
  • 139

2 Answers2

1

Yes, you can!!!

There is an amazing feature in Spring data that allows this:

  1. Create an interface with your custom method:

    public interface UserRepositoryCustom {
    
        User getUserByFirstName();
    }
    
  2. Make your Spring Data interface extends this new interface, as well as the Spring data crud interface (or JPA, Mongo or whatever spring data interface you're extending):

    public interface MySpringDataRepository extends CrudRepository<User, Long>, UserRepositoryCustom {
    
    }
    
  3. Create a class that implements only your custom interface. The name of the class must be Impl, for instance: UserRepositoryImpl:

    public class MySpringDataRepositoryImpl implements UserRepositoryCustom {
        public User getUserByFirstName(){
           //Your custom implementation
        }
    }
    

Now, you only need to inject the Spring data repository in your service and you can use both methods: the spring-data implemented method and your custom implemented method:

@Inject private MySpringDataRepository myRepository;

That's it!!

Look at this section in the documentation:

Spring Data Custom implementations

jfcorugedo
  • 9,793
  • 8
  • 39
  • 47
0

See section 1.3 of the manual for the first requirement:

http://docs.spring.io/spring-data/jpa/docs/1.4.2.RELEASE/reference/html/repositories.html#repositories.single-repository-behaviour

For the second requirement I guess some AOP based solution might work for you well here. See here for example using Spring's AOP support:

logging with AOP in spring?

Community
  • 1
  • 1
Alan Hay
  • 22,665
  • 4
  • 56
  • 110