How to organize CRUD methods for each table?

Asked

Viewed 837 times

4

I would like to know how to organize the CRUD (create, read, update, delete) methods of each class in Java.

An example, to better understand:

Suppose we have the classes Funcionario, Cliente and Produto.

Each of these classes refers to a table in the database, that is, one for employees, one for customers and one for products.

My question is:

It is recommended/best to put the CRUD methods related to each class in themselves or whether it is better to do a class with all database operations.

For example: IncluirFuncionario(), IncluirCliente() and IncluirProduto().

It is better to put each one in his class or make another call OperacoesBD, containing all operations for all classes?

I took the habit of putting everything in one class, because then I used and initialized only once the variable java.sql.Connection connection in the class builder.

  • I think this question is very wide, I recommend you to take a good look at the Java Design Patterns, see this booklet from Caelum: https://www.caelum.com.br/apostila-java-web/

1 answer

2


I think you should keep things within your scope. What has to do with employee, must be in the employee class, client to client, and so on. Imagine a scenario where you have 50 (common) entities. For each of them, a basic CRUD. Your class will have 200 methods, to start with...

You can take these methods out of the class itself, leaving the object independent of database-related issues, but still create separate, specialized classes in the context of the database to handle this persistence. Briefly, separate the models from the data layer.

As for maintaining only one instance of the connection to the bank, you can use static, Singleton, or other drawing that allows you to do this. But stay tuned to problems related to competition and limitations of shared and perhaps intense use of this instance.

As I like - personal - I almost always work in the following sense:

-object class: a POCO class, without any dependence on anyone. I can use it on my display layer and wherever else I want within the application.

-object persistence class: a layer with classes that have CRUD methods and obviously know the POCO class. Each class knows the corresponding scope object, mapping to the database.

-connection class with the database: only instantiated within the persistence class, with the connection controls.

See, in this scenario, if I want to change databases, I just change the class that concerns this scope, the connection, and nothing changes in the rest. Think of layers!

Browser other questions tagged

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