Announcement Announcement Module
No announcement yet.
Custom repository class with Spring Data? Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Custom repository class with Spring Data?


    I'm brand new to Spring Data and trying to get my head wrapped around it a little. I understand that everything (ie: all queries, logic, etc) is generated from interface class, which is backed by the SimpleJpaRepository class. I can foresee this being very practical for any basic queries, etc.

    However, how does one manage the situation if/when I need to create some custom code in the repo class? Something that cannot be addressed with a simple query? Something that may need some business logic? For instance, if I have data that I want my repo to encrypt or decrypt prior to persisting?

    In a standard DAO/repo situation, I could do something along the lines of:

      public void save( T t){
       t.setData( Encryptor.encrypt( t.getData() ) );
       em.persist( t );
      public T getById( Long id ){
       // find object
      T t =  em.find( T.class, id );
      t.setData( Decryptor.decrypt( t.getData() ) );
       return t;
    With the concept of only using an interface-based repo in Spring Data, how do I manage something like that? Do I just extend SimpleJpaRepository for my specific DAO needs and then inject that particular DAO bean into my code instead of a generic @Autowire on the interface name?



  • #2


    Im new to Spring Data aswell... But I think I can give you some hints...
    first, this url:

    has alot of Spring Data material. You can check it out.

    Another thing, Ive costumized my repository by doing this:

    public interface BaseRepository<T, PK extends Serializable> extends PagingAndSortingRepository<T, PK>	
        public List<T> globalSearch(String value, Sort sort);    
    and my specific repository:

    public interface GrupoRepository extends BaseRepository<Grupo, Integer>{
    	List<Grupo> findByDescricaoContaining(String descricao);
    	@Query("select g from Grupo g where g.descricao like '%' || ?1 || '%' OR g.tipo = ?1")
    	List<Grupo> globalSearch(String value, Sort sort);

    notice that I didnt implement the interfaces.. That is still done all by Spring ...
    But if you want to add another layer before the repository i think you should do this:

    public abstract class BaseService<T, PK extends Serializable> {
        private BaseRepository<T, PK> baseRepository;
        public BaseService(BaseRepository<T, PK> baseRepository) {
        public T save(T entity) {
            //encrypt here, before sending it to the repository :)
    	return this.getBaseRepository().save(entity);
    hope I could help