Is it possible to create a Java superclass for basic CRUD functions using spring framework?

When working recently on a project, I noticed that we have several classes with basic CRUD functions and that repeat themselves, their only differences would be some parameters, answers and function calls in different interfaces, my doubt is if it would be possible to create a superclass that has dynamic methods that can receive an object, and use the correct interface to save it, just extending this superclass in the desired class.

My doubt is like I could inherit from a class generic/dynamic methods without the need to write for each class its CRUD.

Example: Class 1

public class ProdutoService{

@Autowired
private ProdutoDAO produtoDAO;

public void salvar(Produto produto){
    produtoDAO.save(produto);
}

public List<Produto> listarTodos(){
    return produtoDAO.findAll();
}

public Produto buscarPorId(String id){
    return produtoDAO.findById(id).orElse(null);
}
}

Class 2

public class ClienteService{

@Autowired
private ClienteDAO clienteDAO;

public void salvar(Cliente cliente){
    clienteDAO.save(cliente);
}

public List<Cliente> listarTodos(){
    return clienteDAO.findAll();
}

public Cliente buscarPorId(String id){
    return clienteDAO.findById(id).orElse(null);
}
}
Author: Allan Almeida, 2020-05-15

1 answers

So André, I believe the way to solution is the use of Generics. Perhaps, something more or less like this (the code below is a reference, a light or just an idea):

public class Box<T> {

      private T t;

      public void add(T t) {
        this.t = t;
      }

      public T get() {
        return t;
      }

      public static void main(String[] args) {
         Box<Integer> integerBox = new Box<Integer>();
         Box<String> stringBox = new Box<String>();

         integerBox.add(new Integer(10));
         stringBox.add(new String("Hello World"));

         System.out.printf("Integer Value :%d\n\n", integerBox.get());
         System.out.printf("String Value :%s\n", stringBox.get());
      }
}

See the following article, very interesting on the topic: using Generics in Java-DevMedia

Hope this helps you!

 0
Author: Allan Almeida, 2020-05-15 17:12:53