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

Asked

Viewed 50 times

1

While working recently on a project, I noticed that we have several classes with basic CRUD and repeating functions, their only differences, would be some parameters, responses and function calls in different interfaces, my question is whether 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 how I could inherit from a class generic/dynamic methods without the need to write to each class their CRUD.

for 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);
}
}

1 answer

0


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 subject: Using Java Generics - Devmedia

I hope it helps you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.