Java: DAO mode
I just got my Web Media Technology job done... I have a little time to write some personal insights on Dao:
What is Dao?
Dao is a data access object data access interface, and data access: the old name of Dao is to deal with the database. Stored in the middle of the business logic and database resources. Dao functions:
1. Dao is used to encapsulate data source... for example, connection conn = daofacotry. createconnection ()..
You can put driver. url. username and passpword in Dao.
In the future, you need to change the database type. For example, if you want to change MSSQL to Oracle, you only need to change the driver. url in getconnection () in daofacory ..
2. Dao also encapsulates all database operations (such as the most basic CRUD operations) in it ..
For example, you want to insert a new user .. so. in Dao, we only need to provide an insertuser (User user) method .. the specific operation is implemented in Dao...
So when we want to call Dao, we only need to know That insertuser (User) is used to insert a new user... instead of how it is implemented.
Generally, Dao is used together with the abstract factory mode...
Factory to create a database and locate specific Dao (for example, userdao .. customerdao ..).. set getconnection to static .. you can also put the public class hibernatesessionfactory in this abstractfactory class...
|
Public class daofactory {
Private Static final sessionfactory sessionfacotory;
// Define a trheadlocal.
Static session currentsession ().....
Public userdao getuserdao () {return New userdaoimpl (sesssion );}
Pulbic otherdao getotherdao () {return New otherdaoimpl (session );}
......
}
Public interface userdao {
Public insertuser (formbean)
Public updateuser (formbean );
}
Then implement the DaO interface: (formbean of struts... vo ..)
Public class userdaoimpl implements userdao {
Private session;
Public userdaoimpl (session ){
This. Session = session;
}...
Public insertuser (formbean ){
..//..
Session. Save (userpo );
..//..
Return formbean;
}
Public formbean updateuser (formbean ){
..//..
Session. Update (userpo );
..//..
Return formbean;
}
}
Finally, define your PO:
Public class userpo {
String firstname, lastname, password ..........
} |