java – Spring data Jpa implement generic methods


I have 3 services with these methods in common create() , deleteById() , findAll() , getById() and update() .

public class AutorService {create(),deleteById(),findAll(),getById(),update(), etc...}

public class GrupoService {create(),deleteById(),findAll(),getById(),update(), etc...}

public class GeneroService {create(),deleteById(),findAll(),getById(),update(), etc...}

I intend to turn them into an interface and create the implementation with business logic in them.

Would it be good practice to interface with these common methods and then extend them? Because every time I have to keep creating these methods.


GenericService with common methods

public interface GenericService<T, I extends Serializable> {

    List<T> findAll();

    T getById(Long id);

    T create(T entity);

    T update(T entity);

    void deleteById(Long id);

AutorService extends GenericService and has its findByName() method

public interface AutorService extends GenericService<AutorEntity,Long>{

    public AutorEntity findByNome(String nome);

AutorServiceImpl implements GenericService with AutorService methods

public class AutorServiceImpl implements AutorService {/*.....*/}


Generally, all your services will have the same crud methods like save , delete , find , findAll , etc. I recommend that you create a generic interface passing the entity type as a parameter. This interface must contain the signature of these methods, and in your service(Interface) you inherit from this generic interface.

For your implementation, you can create a generic abstract class that implements your generic interface and overrides the methods, and in your service(Implementation) you will inherit from this class.

Another good practice is in your abstract class, you create methods like preSave and postSave, so whoever wants to apply some business rule can implement the method and write your rule without messing up the code.

Scroll to Top