DTO and DAO concepts and MVC [closed]
1) Why do we use DTO
and DAO
, and when should we use them. I am developing a GUI
Java software to do with inserting, editing, deleting data. But I am struggling to distinguish between DTO/DAO
and Model
, View
, Controller
(MVC) Structure? Are they similar, which is better to use when interacting with database through Java GUI
.
2) One thing I'm really curious about is whether it is a good practice to have view
and Controller
in one class. If we think about Netbeans
, you can create GUI
Frame Class and add components like JButton
onto the frame, double clicking the button will take you to the actionListener
method(Controller) which appears to be in the frame the data is to be displayed to the user (View). So they're in the same class. Is that completely going against the concept then or not?
Here is what I'm talking about
bad practice to have view and controller in one class?
DTO
is an abbreviation for Data Transfer Object, so it is used to transfer the data between classes and modules of your application.
-
DTO
should only contain private fields for your data, getters, setters, and constructors. -
DTO
is not recommended to add business logic methods to such classes, but it is OK to add some util methods.
DAO
is an abbreviation for Data Access Object, so it should encapsulate the logic for retrieving, saving and updating data in your data storage (a database, a file-system, whatever).
Here is an example of how the DAO and DTO interfaces would look like:
interface PersonDTO {
String getName();
void setName(String name);
//.....
}
interface PersonDAO {
PersonDTO findById(long id);
void save(PersonDTO person);
//.....
}
The MVC
is a wider pattern. The DTO/DAO would be your model in the MVC pattern.
It tells you how to organize the whole application, not just the part responsible for data retrieval.
As for the second question, if you have a small application it is completely OK, however, if you want to follow the MVC pattern it would be better to have a separate controller, which would contain the business logic for your frame in a separate class and dispatch messages to this controller from the event handlers.
This would separate your business logic from the view.