Ibatisnet source code (3)-dataaccess

Source: Internet
Author: User

Dataaccess is a DaO framework. You can configure the DAO implementation used by the application in the configuration file, and provide several packages for specific data access methods to simplify DAO implementation layer development.
The source code of dataaccess is much simpler than that of datamapper.
I. Key Categories
1. Configuration directory
Defines the dataaccess model, which corresponds to the xml configuration file. Therefore, this directory also provides the ability to parse the xml configuration file into the dataaccess object model and serialize the object model into an XML file.
2. Exceptions directory
The exceptions directory contains only one dataaccessexception exception class. Exceptions generated by the dataaccess framework are encapsulated as this class.
3. Interfaces directory
The interfaces directory defines two interfaces: idao and idaosessionhandler. Idao is a flag interface that must be inherited by our DAO implementation class. Idaosessionhandler defines general interfaces for different session processors (sessionhandler. Used to obtain information related to the DaO Manager configuration and the current daosession.
4. Scope directory
Maintain the current configuration and error information.
5. daosessionhandlers directory
The daosessionhandlers directory contains packaging for ADO. NET and sqlmap. For example, simpledaosession Is An ADO. Net implementation of the dataaccess session. sqlmapdaosession is an sqlmappper implementation
Of the dataaccess session. Both classes implement idaosession, which is used to process session-related connections and transactions. The simpledaosessionhandler and sqlmapdaosessionhandler classes both implement the idaosessionhandler interface to obtain the daosession and related configurations from the parsed configuration information.
6. Main directory
The sessionholder class is similar to threadlocal in Java and maintains an idalsession for each thread.
Daomanager is a facade class that reads configuration files and initializes the framework. It maintains different configuration information for different contexts, provides Dao access implementation, and provides connection to the current session) and the transaction method.

II. Introduction and framework Execution Process
Dataaccess framework (Figure omitted ):
Because dataaccess can work with any DAO implementation, the core Library provides.. NET and sqlmap (that is, datamapper) encapsulation. The extended Library provides the encapsulation of Nhibernate, which makes it easier and more practical to compile. The dataaccess document says:
If your application is using raw ADO, the DaO framework will hide classes like datareader, dataadapter, connection, and command. Similarly, if your application
Is using the nhib1_object persistence library, the DaO framework will hide classes like configuration, sessionfactory, session, and hibernateexception. all of these implementation details will be hidden behind a consistent Dao interface layer. furthermore,
The number of different data sources that are being used can be hidden from the View of the application.
Here we will only briefly introduce how to use dataaccess and datamapper. The datamapper class and configuration use the example in datamapper described above.
The following steps are required to use dataaccess:
1. design the DaO interface.
2. Select a DAO implementation.
3. Write the Dao. config configuration file.
4. Use Dao for data operations.
Since the dataaccess framework requires each DAO implementation class, the idao interface must be implemented. To program with the DaO framework, we must define our own Dao interface. It can be designed as a best practice:

1 ). our own Dao interface should be unrelated to any framework, that is, our Dao interface does not need to inherit from the idao interface, and all DaO interfaces are in one or several projects, finally, it is packaged into one or several DLL files, for example:

namespace dao{    public interface IProduct    {        IList GetProductList();        void UpdateProduct(Product pro);    }}

2 ). design a basedao base class that encapsulates a specific Dao-implemented data access method and implements the idao flag interface. For example, we use sqlmapper as the data persistence layer. basedao can be designed as follows:

namespace impl{    public class BaseDao : IDao    {        protected const int PAGE_SIZE = 4;        ///         /// Looks up the parent DaoManager, gets the local transaction        /// (which should be a SqlMapDaoTransaction) and returns the        /// SqlMap associated with this DAO.        ///         /// The SqlMap instance for this DAO.        protected SqlMapper GetLocalSqlMap()        {            DomDaoManagerBuilder builder = new DomDaoManagerBuilder();            builder.Configure();            DaoManager daoManager = DaoManager.GetInstance(this);            SqlMapDaoSession sqlMapDaoSession = (SqlMapDaoSession)daoManager.LocalDaoSession;            return sqlMapDaoSession.SqlMap;        }        ///         /// Simple convenience method to wrap the SqlMap method of the same name.        /// Wraps the exception with a DataAccessException to isolate the SqlMap framework.        ///         ///         ///         ///         protected IList ExecuteQueryForList(string statementName, object parameterObject)        {            SqlMapper sqlMap = GetLocalSqlMap();            try            {                return sqlMap.QueryForList(statementName, parameterObject);            }            catch (Exception e)            {                throw new DataAccessException("Error executing query '" + statementName + "' for list. Cause: " + e.Message, e);            }        }        ///         /// Simple convenience method to wrap the SqlMap method of the same name.        /// Wraps the exception with a DataAccessException to isolate the SqlMap framework.        ///         ///         ///         ///         ///         ///         protected IList ExecuteQueryForList(string statementName, object parameterObject, int skipResults, int maxResults)        {            SqlMapper sqlMap = GetLocalSqlMap();            try            {                return sqlMap.QueryForList(statementName, parameterObject, skipResults, maxResults);            }            catch (Exception e)            {                throw new DataAccessException("Error executing query '" + statementName + "' for list. Cause: " + e.Message, e);            }        }        ...................    }}


3). The specific DAO implementation class inherits from basedao and implements its own Dao interface. And use the basic functions provided by basedao, and all DaO implementations are packaged into one or several DLL files in one or more projects, in this way, you can simplify maintenance and easily modify the daofactory configuration, for example:

namespace impl{    public class ProductDAO : BaseDao, IProduct    {        #region IProduct Members        public IList GetTheProductList()        {            IList prods = base.ExecuteQueryForList("getProduct", null);            Console.WriteLine("public System.Collections.IList GetProductList():");            foreach (Product p in prods)            {                Console.WriteLine("id:{0};Org:{1};PlatId:{2}", p.Id, p.Org, p.PlatId);            }            return prods;        }        public void UpdateTheProduct(Product pro)        {            base.ExecuteUpdate("updateNews", pro);            Console.WriteLine("public void UpdateProduct(Domain.Product pro) finished.");        }        #endregion    }}

Configuration file -- Dao. config
<? XML version = "1.0" encoding = "UTF-8"?>
<Daoconfig xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"
>

<Providers resource = "providers. config"/>

<Context ID = "sqlmapdao" default = "true">

<Database>
<Provider name = "oracle9.2"/>
<Datasource name = "ibatisdemo" connectionstring = "Data Source = data-89; persist Security info = true; user id = data; Password = Data"/>
Database>

<Daosessionhandlers>
<Daosessionhandler id = "sqlmap">
<Property name = "resource" value = "sqlmap. config"/>
Daosessionhandler>
Daosessionhandlers>

<Daofactory>
<Dao interface = "Dao. iproduct, Dao" implementation = "impl. productdao, impl"/>
Daofactory>
Context>

Daoconfig>

Use DAO for data storage operations

Namespace oratest {class program {public static void main () {// read the configuration file to create a daomanager and obtain the sqlmapdao context instance. Domdaomanagerbuilder builder = new domdaomanagerbuilder (); builder. Configure (); daomanager = daomanager. getinstance ("sqlmapdao"); // obtain and initialize the specific implementation class of the iproductdao interface. Iproduct Dao = daomanager [typeof (iproduct)] as iproduct; // use DAO for programming. Dao. getproductlist (); product P = new product (); p. ID = "fr20t0000003000000096426"; p. org = "orgid2"; Dao. updateproduct (p );}}}

As shown in the preceding figure, the DaO framework provides great flexibility for programming. In addition, you can change DAO implementation by modifying Dao. config during release or even running.

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.