Comparison between ADO. NET and ORM (2): Implementing CRUD with nhib.pdf

Source: Internet
Author: User
Note: I personally feel that large-scale development in the Java field cannot leave ORM. The so-called SSH is Spring + Struts + Hibernate, in addition to being informed that you can use JDBC to operate databases when learning basic knowledge, many books refer to using the Hibernate ORM tool to operate data. There are many ways to operate databases in. NET,

Note: I personally feel that large-scale development in the Java field cannot leave ORM. The so-called SSH is Spring + Struts + Hibernate, in addition to being informed that you can use JDBC to operate databases when learning basic knowledge, many books refer to using the Hibernate ORM tool to operate data. There are many ways to operate databases in. NET,

Note: I personally feel that large-scale development in the Java field cannot leave ORM. The so-called SSH is Spring + Struts + Hibernate, in addition to being informed that you can use JDBC to operate databases when learning basic knowledge, many books refer to using the Hibernate ORM tool to operate data. In. there are multiple methods to operate databases in. NET, except that the most direct method is to use ADO. in addition to. NET, you can also use the Hibernate in. NET. If you are skeptical about third-party ORM, you can also use the implementation from Microsoft, the root of which is the emergence of Linq or EntityFramework.
Most of them have been used since the beginning.. NET developers may. NET has a crush on using ADO. NET can make full use of our early SQL knowledge, and out of consideration of performance, some people are right. the ORM in NET also maintains a kind of wait-and-see attitude, including myself. However, even if we don't need it in actual development, it doesn't mean that we cannot understand and compare these technologies. There is always a reason for the emergence and extinction of anything. We can understand their advantages and advantages. So I spent a few weekends using ADO. NET, nhib.pdf, Linq, and EntityFramework are used to Create, Read, update, and delete data in a single database table. CRUD (C: Create/R: Read/U: update/D: Delete ).
By comparing the implementation of the same function, you can determine which method is more suitable for you. Note that if you use EntityFramework in VS2008, you need to install VS2008SP1.
This week we will show you how to use nhibloud to implement the CRUD function. In order to facilitate comparison, we will use the same database and table as last time, and also implement the same function. Nhibing Is An ORM framework. The so-called ORM is Object Relational ing. It is a technology that establishes ing relationships between data in Relational databases and objects in object-oriented languages, we can operate data like an object. nhib.pdf saves our changes to the object to the database, and is also responsible for querying data from the database as an object, in this way, developers can process SQL and ADO.. NET saves some time and energy for processing business logic.
1. Preparation
First, we need to download the NHibernate framework from the Internet. This can be downloaded from its official website www.nhibernate.org. When Zhou Gong writes this article, he can download the latest version 2.1.2.GA from the Internet. If the downloaded package is compressed, decompress the package and you will see four folders. Their names and functions are as follows:
Configuration_Templates: Example of the configuration file for storing the nhibana database to connect to. In this folder, there are configuration samples for connecting Firebird, SQL Server, MySQL, Oracle, PostgreSQL, and SQLite databases respectively, you can select the sample code and change the data source based on the actual database used.
Required_Bins: stores the class library files required for running NHibernate. It also contains a third-party open-source log framework Log4Net, we recommend that you copy all dll files in this folder to the bin folder of the project if you are not sure whether the class libraries will be used.
Required_For_LazyLoading: stores the framework files required for the delayed loading feature. Three implementations are provided under this folder. Select one to copy all the dll files under it to the bin folder where the project is located. In this example, Castle is selected.
Tests: stores test files. In this folder, there is a file named ABC. hbm. xml file. This is an example of the configuration file corresponding to a data table. We don't need any files in this folder, but we will use it later. hbm. xml file.
2. Create a project
We create a project. The project type can be selected based on the situation. Because I will use NUnit to perform unit tests on the project in the future, the class library project is created.
After the project is successfully created, copy the following files to the bin directory of the project:
Antl3.runtime. dll
Castle. Core. dll
Castle. DynamicProxy2.dll
Iesi. Collections. dll
Log4net. dll
Nhib.pdf. ByteCode. Castle. dll
Nhib.pdf. dll
Add references to these dll files in the project, as shown in:

3. write code
3.1 create a NHibernate configuration file
The NHibernate configuration file is in a relatively fixed format. You can extract the file from the Downloaded archive to the Framework file, which is located in the Configuration_Templates folder.
Add an xml file named hibernate. cfg. xml to the current project. The format of this file on Zhou Gong's machine is as follows:
<? Xml version = "1.0" encoding = "UTF-8"?> <Hibernate-configuration xmlns = "urn: nhibernate-configuration-2.2"> <session-factory> <property name = "connection. driver_class "> nhib.pdf. driver. sqlClientDriver </property> <property name = "connection. connection_string "> Data Source = zhou; Initial Catalog = AspNetStudy; User ID = sa; Password = jerry; </property> <property name =" adonet. batch_size "> 10 </property> <property name =" show_ SQL "> true </property> <property name =" dialect "> nhib.pdf. dialect. msSql2005Dialect </property> <property name = "use_outer_join"> true </property> <property name = "command_timeout"> 10 </property> <property name = "query. substitutions "> true 1, false 0, yes 'y', no 'n' </property> <property name =" proxyfactory. factory_class "> nhib.pdf. byteCode. castle. proxyFactoryFactory, nhib.pdf. byteCode. castle </property> <mapping assembly = "NHibernateDemo"/> </session-factory> </pibernate-configuration>

If you also use SQL Server2005 as the database, you need to change the connection. the database connection information in connection_string is your local connection information, and the actual situation changes the assembly value to your current project compiled assembly name.
Note that you need to change the property of hibernate. cfg. xml to the copy property to always copy, as shown in:

3.2 Create a ing File
The ing file contains the metadata required by the object/link, including the persistence class used and the ing to the database. Nhib knows how to load and store persistent objects through ing files.
Add an xml file named UserInfo. hbm. xml to the project. The content of this xml file is as follows:
<? Xml version = "1.0" encoding = "UTF-8"?> <Hibernate-mapping xmlns = "urn: nhibernate-mapping-2.2 "assembly =" NHibernateDemo "namespace =" NHibernateDemo "> <class name =" UserInfo "> <id name =" UserId "column =" UserId "> <generator class =" native "/> </id> <property name =" UserName "/> <property name =" RealName "/> <property name =" Age "/> <property name =" Sex "/> <property name =" Mobile "/> <property name =" Phone "/> <property name =" Email "/> </class> </pibernate-mapping>
Note: If you want to obtain the information in edit hibernate. cfg. xml or UserInfo. hbm. xml smart tips, you can download the nhibernate-configuration.xsd and nhibernate-mapping.xsd files in the nhib.pdf compressed package copy to a special folder in VS, on the local machine last week the public installed VS2008 on drive C, copy the file mentioned above to the C:/Program Files/Microsoft Visual Studio 9.0/Xml/Schemas directory. You need to copy the file according to your actual situation.
You need to change the attributes of this file to "embedded resources", as shown in:

3.3 create a persistence class
Create a class file named UserInfo. cs in the current project. The code for this class is as follows:

Using System; using System. collections. generic; using System. text; namespace NHibernateDemo {// <summary> // persistence class of the UserInfo table in the database /// Author: Zhou Gong // blog address: http://blog.csdn.net/zhoufoxcn // Date: 2010-03-19 // </summary> public class UserInfo {public virtual int UserId {get; set;} public virtual string UserName {get; set;} public virtual string RealName {get; set;} public virtual int Age {get; set;} public virtual bool Sex {get; set;} public virtual string Mobile {get; set;} public virtual string Phone {get; set ;}public virtual string Email {get; set ;}}}
Note: nhibter implements Object persistence by using getter and setter operations of the attribute, and requires that the class cannot be sealed, and the method and attribute must be virtual.
3.4 compile helper classes
The preceding file nhib can be used to implement link ing. Here we compile the relevant auxiliary class Code as follows:Using System; using System. collections. generic; using System. text; using Iesi. collections; using nhibctions; using NHibernate. cfg; namespace NHibernateDemo {// <summary> /// note: this class is used to demonstrate the usage of CRUD in NHibernate /// by Zhou Gong (Zhou Jinqiao) /// Date: 2010-03-07 // </summary> public class NHibernateCRUD {private ISessionFactory sessionFactory; public NHibernateCRUD () {sessionFactory = new Configuration (). configure (). buildSes SionFactory ();} public ISession GetSession () {return sessionFactory. openSession () ;}/// <summary> // Count the total number of users /// </summary> /// <returns> </returns> public int Count () {# region method 1 // ISession session = GetSession (); // ISQLQuery query = session. createSQLQuery ("select count (1) from UserInfo"); // int count = query. list <int> () [0]; // session. close (); // return count; # endregion # region method 2 ISession s Ession = GetSession (); IQuery query = session. createQuery ("select count (c. userId) from UserInfo c "); // Note: query cannot be used for the count function. list <int> (), because the default returned value type is long // otherwise, GenericADOException is thrown. The exception description is: cocould not execute query [SQL: SQL not available] // InnerException: system. argumentException, InnerException Description: "the value" * "is not" System. int32 type, which cannot be used in this generic set. /R/n Parameter Name: value int count = (int) (query. list <long> () [0]); session. close (); return count; # endregion} // <summary> // create a user // </summary> // <param name = "info"> user entity </param> // /<returns> </returns> public int Create (UserInfo info) {ISession session = GetSession (); int newId = (int) (session. save (info); session. flush (); session. close (); return newId;} // <summary> // read user information /// </summary> /// <par Am name = "userId"> User ID </param> // <returns> </returns> public UserInfo Read (int userId) {ISession session = GetSession (); userInfo info = session. get <UserInfo> (userId); session. close (); return info ;} /// <summary> /// update user information /// </summary> /// <param name = "info"> user entity </param> /// <returns> </returns> public void Update (UserInfo info) {ISession session = GetSession (); session. update (info); session. fl Ush (); session. close ();} /// <summary> /// delete a user /// </summary> /// <param name = "userId"> User ID </param> /// <returns> </returns> public void Delete (int userId) {ISession session = GetSession (); // you can directly use the parameter value, ":" + parameter name ,? (Similar to using parameterized SQL statements in Access, assigning values to parameters depends on the order in which the parameters appear) and other methods such as IQuery query = session. createQuery ("delete from UserInfo where UserId =: UserId"); // If ":" + parameter name is used, when assigning a value to a parameter, you do not need to add the ":" sign before the parameter name, such as query. setInt32 (": UserId", userId); an error is returned. setInt32 ("UserId", userId); int affectedRows = query. executeUpdate (); session. close (); // return affectedRows ;} /// <summary> /// delete a user /// </summary> /// <param name = "userId"> user entity </param> /// <returns> </returns> public void Delete (UserInfo info) {ISession session = GetSession (); session. delete (info); session. flush (); session. close ();} /// <summary> /// obtain the user with the largest number in the User table /// </summary> /// <returns> </returns> public int GetMaxUserId () {ISession session = GetSession (); IQuery query = session. createQuery ("select max (UserId) from UserInfo"); int userId = query. list <int> () [0]; session. close (); return userId ;}}}


Unit test code 3.5

Using System; using System. collections. generic; using System. linq; using System. text; using NUnit. framework; using NHibernateDemo; namespace NUnitTest {[TestFixture] public class NHibernateTest {private NHibernateCRUD instance = null; [SetUp] public void Initialize () {instance = new NHibernateCRUD ();} [Test] /// <summary> /// Count the total number of users /// </summary> /// <returns> </returns> public void Count () {Assert. greater (instance. count (), 0 );} [Test] /// <summary> /// create a user /// </summary> /// <param name = "info"> user entity </param> // /<returns> </returns> public void Create () {UserInfo info = new UserInfo () {Age = 12, Email = "zzz@ccav.com", Mobile = "13812345678", Phone = "01012345678", RealName = "test" + DateTime. now. millisecond. toString (), Sex = true, UserName = "zhoufoxcn" + DateTime. now. millisecond. toString ()}; instance. create (info );} [Test] /// <summary> /// read user information /// </summary> /// <param name = "userId"> User ID </param>/ // <returns> </returns> public void Read () {UserInfo info = instance. read (1); Assert. notNull (info );} [Test] /// <summary> /// update user information /// </summary> /// <param name = "info"> user entity </param>/ // <returns> </returns> public void Update () {UserInfo info = instance. read (1); info. realName = "test" + DateTime. now. millisecond. toString (); instance. update (info );} [Test] /// <summary> /// delete a user /// </summary> /// <param name = "userId"> User ID </param> // /<returns> </returns> public void DeleteByID () {int userId = instance. getMaxUserId (); instance. delete (userId );} [Test] /// <summary> /// delete a user /// </summary> /// <param name = "userId"> user entity </param> // /<returns> </returns> public void Delete () {int userId = instance. getMaxUserId (); UserInfo info = instance. read (userId); Console. writeLine ("MaxUserId =" + userId); instance. delete (info );}}}
4. Comments
One of the major advantages of Using ORM is that there is little or no need to write database records to code mapped to objects, and in most cases, you do not need to write SQL code (Instead, HSQL ). When using ADO. I often have this experience in the NET era, because database changes may need to change the relevant code from the display to the database access layer, you also need to change the code written by yourself to convert the database record to the object. Now you only need to change the code of the ing file and persistence class, in addition, we can use the object-oriented method to operate data. You can see that the CRUD code for the database in NHibernateCRUD is better than that for the database directly using ADO. net crud operations code is much simpler, which is the charm of ORM.
Of course, Using ORM also has some disadvantages. After all, ORM uses ADO at the underlying layer. NET, for an experienced developer, it is possible to directly use ADO. NET is more efficient than using nhib.pdf. The cache mechanism of nhib.pdf can alleviate this problem to some extent. However, when the data volume is about 10 million, this problem is quite prominent. In some cases where the data volume is below 1 million, there is no problem with the rational use of nhib.pdf.
Zhou Gong
2010-03-19

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.