Step by step-build your own ORM series-start

Source: Internet
Author: User
ArticleDirectory
    • I. Opening
    • II. Introduction to this chapter
    • Iii. Contents of this Chapter
    • Iv. Application Analysis of ORM
    • V. ORM design analysis
    • Vi. Summary in this Chapter
    • VII. Series progress
    • 8. next announcement
I. Opening

First, many colleagues in the garden have discussed the ORM-related frameworks and their advantages and disadvantages. Although I have discussed this article a little late, it has advantages over disadvantages. This article only briefly introduces me to discuss

The purpose of ORM and the reason for discussing the mature things that have been discussed by everyone.

Let's take a look at the advantages and disadvantages of ORM:

This article will analyze in detail why we need to use orm and analysis and modeling in the previous section of ORM.

II. Introduction to this chapter

This article mainly analyzes the advantages and disadvantages of the ORM framework and the trade-offs in the project, finds Breakthrough points, and analyzes the basic functions that the ORM should possess in a graphical way and how to build the core modules in the Orm. This is simple

List the core modules in the ORM:

The following describes and analyzes the implementation scheme.

Iii. Contents of this Chapter

1. Summary.

2. Introduction to this chapter.

3. Content in this chapter.

4. Application Analysis of ORM.

5. ORM design analysis.

6. Summary in this chapter.

7. Series progress.

8. next announcement.

Iv. Application Analysis of ORM

First of all, in software development, we all know the significance of OO Object-oriented Thinking to our existing software development. We can understand the process of software development as an abstract process of the real society. The concept of object-oriented

The real world is abstracted as all objects, and all activities are completed through interaction between objects. Prior to the emergence of OO, software development was a process-oriented development idea. Process-oriented relationships are processes rather than objects. In an action

The steps in the process are solved through a series of functions.

Object-oriented means that everything is regarded as an object, and the process is the interaction between objects or the activity within objects.

We know that all popular databases are relational databases with two-dimensional database structures. How can we map an object to this object? This has become a matter of more concern to us. At this time, the ORM idea

To solve this problem.

Reflects the relationship between an object and a database table. An object corresponds to a row record in a database table. The query method in DDL operations is used to map Row Records in database tables to multiple object pairs.

Image center. Through the DDL operation method provided by Orm, the data of the object is persisted to the corresponding database table.

Another issue that needs to be paid attention to is how to achieve one-to-one correspondence between attributes in an object and columns in a database table when the attributes in the object are added or reduced or the structure in the database table changes. This is an Orm.

This is a headache because ORM cannot achieve automatic synchronization. Of course, the well-known Nhibernate is flexible in this regard, which must be affirmed. Of course, in this series, we also

It will explain in detail the implementation ideas and solutions, and how to solve the synchronization problem when the structure of the entity and database table changes. Of course, this is related to the implementation of the Orm.

Orm provides me with the following convenience:

Of course, the ORM framework is not omnipotent, and there must be some shortcomings. Let's look at the shortcomings of ORM:

Through the above analysis, we have a simple understanding of the advantages and disadvantages of ORM, so how to apply it in the project, we must use a technology to develop strengths and circumvent weaknesses, so ORM is the same principle, if we have a large number of DDL operation statements in the project and the relationship between multiple entities in the business logic is not very close, we will use the ORM technology.

If you have a large number of associated queries for multiple tables in the project and the logical relationships between tables are complex, we do not recommend Using ORM for processing. This will not only increase the complexity of the project, but also increase the maintenance cost. For example

Analysis System. It is troublesome to implement it using Orm.

V. ORM design analysis

First, let's take a look at the general component model of database access:

This section outlines several common types of databases and uses the database access component in the ORM to access the database. Of course, here we define the form of a unified interface for database access to make all the data

The Library category class inherits this interface by default.

InstanceCodeAs follows:

 

Public interface idbaccessor {// <summary> // execute update, delete, insert statement method /// </Summary> /// <returns> returns the number of affected rows </returns> int excute (); /// <summary> /// query execution method /// </Summary> void query ();}

The interface only defines four basic operations in a simple DDL language.

The following describes how to implement different databases.

Sqlserver Database

 

 public class sqlserver: idbaccessor {# region idbaccessor member private string commandstr = string. empty; Private Static string connectionstring = ""; private system. data. idbconnection sqlconnection = new system. data. sqlclient. sqlconnection (connectionstring); Public int excute () {If (sqlconnection. state! = System. data. connectionstate. open) sqlconnection. open (); try {using (system. data. idbcommand command = sqlconnection. createcommand () {command. commandtext = commandstr; return command. executenonquery () ;}} catch (system. exception) {return-1 ;}finally {}} public void query () {}# endregion }

Oracle Database

 

Public class ORACLE: idbaccessor {# region idbaccessor member private string commandstr = string. empty; Private Static string connectionstring = ""; private system. data. idbconnection oraconnection = new system. data. oracleclient. oracleconnection (connectionstring); Public int excute () {If (oraconnection. state! = System. data. connectionstate. open) oraconnection. open (); try {using (system. data. idbcommand command = oraconnection. createcommand () {command. commandtext = commandstr; return command. executenonquery () ;}} catch (system. exception) {return-1;} finally {} public void query () {Throw new notimplementedexception () ;}# endregion}

We will not illustrate the other types of databases one by one. Of course, I have not considered defining database connections as interfaces in these interfaces so that all of them can be inherited from these interfaces, because this is not

The focus of this chapter is to briefly analyze and design how to achieve universal access to the data layer.

The following describes the implementation of object link ing.

We have two common methods at present. The first method should be familiar to everyone, whether it is hibernate in Java or.. net.

The table column attribute in the database corresponds to the object attribute one by one. The second method is to write the ing between database columns and entities in a class file by hard encoding.

The following describes the advantages and disadvantages of the two methods:

The above describes their respective shortcomings.

Of course, the above two forms have their own advantages and disadvantages. We have already told you that the existing open-source frameworks in the XML configuration file adopt nhib.pdf. There are actually many frameworks using class file ing,

Their ideas are relatively the same. Whether it's XML files or file-like files, their main point of view is how to map object attributes to database table fields. This is the core content.

Next we will provide a simple idea to complete such ing. Of course, we will give an example in the form of class files.

In fact, many people in the blog Park have written examples of class file ing. Of course, I am only here to discuss the shortcomings. I would like to ask more comments.

The method I provided is to implement ORM ing through the concept of Attribute + reflection.

The Code is as follows:

 

/// <Summary> /// attribute of the field in the model /// </Summary> [attributeusage (attributetargets. all, allowmultiple = false)] public class propertyattribute: attribute {private string dbcolumnname; private bool isprimary; private dbtype; private object defaultvalue; private bool isidentify; private int length; public String dbcolumnname {get {return this. dbcolumnname;} set {This. dbcolumnname = value ;}} public bool isprimary {get {return this. isprimary;} set {This. isprimary = value ;}} public bool isidentify {get {return this. isidentify;} set {This. isidentify = value ;}} public dbtype {get {return this. dbtype;} set {This. dbtype = value ;}} public object ultultvalue {get {return this. defaultvalue;} set {This. defaultvalue = value ;}} public int dblength {get {return this. length;} set {This. length = value ;}} public propertyattribute (string dbname, bool isprimery, dbtype type, object dvalue) {This. dbcolumnname = dbname; this. isprimary = isprimery; this. dbtype = type; this. defaultvalue = This. getdefaultvalue ();} private object getdefaultvalue () {return new object ();} public propertyattribute (string dbname) {This. dbcolumnname = dbname; this. isprimary = false; this. dbtype = dbtype. string; this. defaultvalue = This. getdefavalue value ();} public propertyattribute (string dbname, bool isprimery) {This. dbcolumnname = dbname; this. isprimary = isprimery; this. dbtype = dbtype. string; this. defaultvalue = This. getdefavalue value ();} public propertyattribute (string dbname, bool isprimery, dbtype type) {This. dbcolumnname = dbname; this. isprimary = isprimery; this. dbtype = type; this. defaultvalue = NULL ;}}

The features defined on field attributes are shown above. Let's look at the features of the table:

 

 
/// <Summary> /// table-based custom feature class /// </Summary> [attributeusage (attributetargets. all, allowmultiple = false)] public class tableattribute: attribute {private string dbtablename; Public tableattribute (string dbname) {This. dbtablename = dbname;} Public String tablename {get {return this. dbtablename;} set {This. dbtablename = value ;}}}

The usage of the Object layer is as follows:

 

/// <Summary> /// Administrator account ID /// </Summary> [propertyattribute ("", false, system. data. dbtype. int32, 0)] public int adminid {set {_ adminid = value;} get {return _ adminid ;}}

Table-based features are as follows:

 

 
[Tableattribute ("es_memberaccount")] public class account {Public Account (){}}

 

The following describes how to handle the SQL statement layer:

 

/// <Summary> /// return the database table name corresponding to the model /// </Summary> /// <typeparam name = "T"> </typeparam> // /<Param name = "model"> </param> // <returns> </returns> Public String dbtablename <t> (T Model) {string dbname = string. empty; DPM. common. tableattribute ATTR = NULL; object [] attributes = model. getType (). getcustomattributes (typeof (dpm. common. tableattribute), true); If (attributes. length> 0) {ATTR = (dpm. common. t Ableattribute) attributes [0];} If (ATTR! = NULL) dbname = ATTR. tablename; return dbname ;} /// <summary> /// return all data columns in the database table /// </Summary> /// <typeparam name = "T"> </typeparam> // /<Param name = "model"> </param> // <returns> </returns> Public String initdbcolumns <t> (T Model) {stringbuilder commandbuilder = new stringbuilder (); DPM. common. propertyattribute ATTR = NULL; foreach (propertyinfo property in model. getType (). getproperties () {object [] attributes = property. getcustomattributes (typeof (dpm. common. propertyattribute), true); If (attributes. length> 0) {ATTR = (dpm. common. propertyattribute) attributes [0];} commandbuilder. append (ATTR. dbcolumnname + ",");} return commandbuilder. tostring (). substring (0, commandbuilder. tostring (). length-1 );}
Vi. Summary in this Chapter

This chapter briefly describes the basic concepts of ORM implementation, the advantages and disadvantages of using the ORM framework, and how to reasonably analyze and apply it in the project. The following is a brief summary of the content described in this chapter.

This chapter mainly describes the advantages of ORM: reduced workflow, high reusability, fast development speed, and more focus on business development. In addition to complex implementation of DDL operations, basically

Can be processed normally. Disadvantages: one-to-many or many-to-many associations cannot meet the requirements well, and performance may be affected. In the project, determine whether to enable

Use the ORM framework to solve the problem.

VII. Series progress

1. Step by step-build your own ORM series-start

2. Step by step-build your own ORM series-data access layer

3. Step by step-build your own ORM series-configure the management layer

4. Step by step-build your own ORM series-object ing layer [on]

5. Step by step-build your own ORM series-object ing layer [medium]

6. Step by step-build your own ORM series-object ing layer [bottom]

7. Step by step-build your own ORM series-test the ORM framework

8. Step by step-build your own ORM series-bottleneck and Optimization

9. Step by step-build your own ORM series-instance

8. next announcement

Next we will explain how to implement a common data access layer, introduce in detail how to design a common data access layer, and adopt two principles in the design model: some design specifications and original specifications such as low coupling and High Cohesion

. You are welcome to give suggestions and suggestions.

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.