Software Design: how to design the DaO Layer

Source: Internet
Author: User
Tags add time

I am still a bit vague about the design of the DaO layer. There are five or six projects in large and small projects, and there are three or four databases in charge.

Two methods have been used to design the DaO layer:

Solution 1:Each table corresponds to a DAO class (the interface is also available). Each Dao completes addition, deletion, modification, and query of the table and the query operations required by the business. In this design, if there are many tables, there will be many classes and a lot of repeated code will appear, because each DAO will involve basic addition, deletion, modification, and query.

Solution 2:Write a basic class to complete addition, deletion, modification, and query. Other tables with additional business requirements are written into one class separately. However, this class only includes additional functions. When writing basic classes, you must pay strict attention to them. Because similar ing implementations are used, you must design the same table structure as the entity classes, because the SQL statement for adding, deleting, modifying, and querying databases in this class is completed by extracting the object class name and attributes in the object class.

Here is a basic addition method (VB.net implementation ):

Public class sqldao: Implements Dal. idao

Private sqldr as sqldatareader
Private sqlcon as sqlconnection
Private sqlcmd as sqlcommand
'Get the database connection string from the configuration file app. config.
Private strconnect as string = configurationmanager. receivettings ("strcon ")
'Get the class name
Private strclassname as string
'Get the class type
Private mtype as type
'Get the property set
Private mpros as propertyinfo ()

'Connect to the database in the initialization method
'Public sub Init (byval OBJ as object) implements idao. init
'Sqlcon = new sqlconnection (strconnect)

''Initialize necessary types in the constructor
'Strclassname = typename (OBJ)
'Mtype = obj. GetType ()
'Mpros = mtype. getproperties
'End sub

'A private Method for connecting to the database
Private function getcon () as sqlconnection implements idao. getcon
Try
If (sqlcon. State = connectionstate. Closed) then
Sqlcon. open ()
End if
Catch ex as exception
Msgbox ("when opening the database:" + ex. Message)
End try

Return sqlcon
End Function

''' <Summary>
''' Adds the object to the corresponding table. The parameter is an object and the return value is int type, indicating the number of affected rows.
''' </Summary>
''' <Param name = "entity"> </param>
''' <Returns> integer </returns>
''' <Remarks> </remarks>
Public Function addobj (of T) (byval entity as t) as integer implements idao. addobj
Dim res as integer = 0' is used to return the number of rows affected by this operation.
'Define a single attribute
Dim mpro as propertyinfo
'Define SQL Parameters
Dim para as sqlparameter
Dim strfields as string = ""
Dim strcondition as string = ""
Dim strsql as string = ""
For each mpro in mpros
'This loop is used for parameter combination
'No need to add time when adding
Strfields = CSTR (TRIM (mpro. getvalue (entity, nothing) ') 'Get the attribute value
If strfields <> "0" and strfields <> "00:00:00" and strfields <> "" then

Strsql = strsql + "@" + mpro. Name + ","
'Form a field name in combination
Strcondition = strcondition + mpro. Name + ","
End if
Next
'Insert the final parentheses.

Strsql = left (strsql, Len (strsql)-1) + ")"
Strcondition = left (strcondition, Len (strcondition)-1) + ")"
Strsql = "insert into" + strclassname + "(" + strcondition + "values (" + strsql
'Msgbox (strsql)
Try
Using scmd as new sqlcommand (strsql, getcon)
'Set the execution Method
Scmd. commandtype = commandtype. Text
For each mpro in mpros
'Assign a value to the parameter
'Dim stra as string = mpro. getvalue (OBJ, nothing)
'Generally, you do not need to add time, except for the drop-down table.
Strfields = CSTR (TRIM (mpro. getvalue (entity, nothing) ') 'Get the attribute value
If strfields <> "0" and strfields <> "00:00:00" and strfields <> "" then
Para = new sqlparameter ("@" + mpro. Name, mpro. getvalue (entity, nothing ))

Scmd. Parameters. Add (para)
End if
Next
Res = scmd. executenonquery
End using
Catch ex as exception
Msgbox ("when adding objects:" + ex. Message)
End try
Return res' return the number of rows affected by the operation
End Function
End Class

I have also checked some information on the Internet over the past few days, mainly about how to design the DaO layer. The most direct design scheme is that each table corresponds to a Dao, which means that the code is too repetitive, however, the basic code is designed in this way, and there are all ready-made tools to directly generate corresponding additions, deletions, modifications, and queries based on the table.

However, because too many code needs to be repeated, someone suggested this method:

Public interface basedao <t> {
Public void create (t );
Public void Delete (t );
Public void Update (t );
}

Public interface winddao extends basedao <Wind> {
Public void other (Wind );
}

Place basic addition, deletion, modification, and query in a basic interface through generics. Others only need to implement this interface. If there are additional requirements, they can add their own methods. This is a typical inherited application. But to be honest, this method cannot reduce the amount of code.

This is really hard to understand. Some people in the Forum said: "In fact, you can inject basedao into baseservice, so that you don't need to write a class for every Dao, I would be very grateful if I had a great opportunity to give advice.

Cao Shige:

When I encounter a problem, I will use the 3w principle of Software Engineering (what, why, how) to think about it.

First, what:

 

  • Dao (Data Access Object), a data access object. Since it is an object, it is encapsulated. It encapsulates a series of interfaces for business and related data to interact with the database.
  • Why:

  • 1. the user does not need to understand the details of this object, but only needs to understand the interface of this object to interact with the database, which facilitates the user's use.
  • 2. Design a DaO layer. All the above business layers call the DaO layer interface to realize software reusability.
  • 3. The existence of the DaO layer separates the business logic layer from the database access code.
  • 4. The Dao layer can handle the differences between different databases, so that the software has little code to change during database migration, such as Oracle, MySQL, and DB2.
  • 5. The encapsulation of the DaO layer does not require developers to directly interact with the database (with the DaO layer, through the DaO layer), increasing the security of the database. And so on.
  • How:Through the above why analysis, we should pay attention to the following when designing the DaO layer:

  • 1. provides a wide range of interfaces for users to call,
  • 2. Business content cannot be involved in Dao. A Dao layer interface corresponds to a database operation (atomic ).
  • 3. consider migrating the software to an inaccessible database.
  • 4. the Dao layer is a bridge between business and related data and database interaction. Therefore, the DaO layer needs to encapsulate a series of database operations, including adding, deleting, modifying, querying, and database transactions, stored Procedures, triggers, and so on. One thing to note is the transaction processing. The Dao layer is generally not responsible for the transaction processing and leaves the transaction processing to the business layer. The reason is: if the business logic needs to call multiple Dao methods at a time, once a DAO method fails, resulting in rollback, the executed Dao will not be able to roll back.
  • In short, the DaO layer is used to decouple business operations from database operations. business changes do not affect data access, while data access methods change (the interface remains unchanged ), does not affect the business, so that all parts of the system are independent of each other. The operations at the DaO layer are a decomposition of the business, and a complete business is decomposed into related tables in the database.

     

    Original article, reprint please indicate the source: http://www.the5fire.net /? P = 168
    Fixed Link to this article: the5fire technical blog | if you like my blog, you canSubscribe to this blogTo receive updates in time

    Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.