How to organize the CRUD methods for each table?

4

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

An example, to get better at understanding:

Suppose we have the Funcionario , Cliente and Produto classes.

Each of these classes refers to a table in the database, that is, one for the employee, the other for the customer, and the other for the products.

My question is:

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

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

Is it better to put each one in your class or make another call OperacoesBD , which contains all operations for all classes?

I took the custom of for everything in a class only, hence I used and initialized only once the variable java.sql.Connection connection in the class constructor.

    
asked by anonymous 10.06.2015 / 19:33

1 answer

2

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

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

As for maintaining only one instance of the connection to the database, you can use static classes, singleton, or other drawing that allows you to do so. But be aware of competition issues and limitations of shared and perhaps intense use of this instance.

How I like it - people - I almost always work in the following way:

- Object class: A POCO class, with no 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 the CRUD methods and obviously knows the POCO class. Each class knows the object of the corresponding scope, doing the mapping to the database.

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

Note that in this scenario, if I happen to want to change databases, I only change the class that relates to this scope, the connection, and nothing changes in the rest. Think of layers!

    
10.06.2015 / 20:22