[Reference] [Castle ar] 4. crud

Source: Internet
Author: User
Tags findone
Http://www.rainsts.net/article.asp? Id = 486
The crud operations of activerecord are basically completed by the static method of activerecordbase. Its instance (including sub-type) methods and activerecordmediator only call the packaging of these static methods. Of course, the activerecordbase method is the packaging of the Nhibernate session method.

We will use the following entity to briefly demonstrate the use of common methods. [Activerecord ("users")]
Public class user: activerecordbase <user>
{
Private int ID;

[Primarykey (primarykeytype. Identity, access = propertyaccess. fieldcamelcase)]
Public int ID
{
Get {return ID ;}
}

Private string name;

[Property (unique = true, notnull = true)]
Public string name
{
Get {return name ;}
Set {name = value ;}
}
}

To observe the SQL statements generated by Nhibernate, we add the "show_ SQL" configuration in the configuration file. <? XML version = "1.0" encoding = "UTF-8"?>
<Activerecord>
<Config>
<Add key = "hibernate. Connection. driver_class" value = "nhib.pdf. Driver. sqlclientdriver"/>
<Add key = "hibernate. dialect" value = "nhib.pdf. dialect. mssql2000dialect"/>
<Add key = "hibernate. Connection. provider" value = "nhib.pdf. Connection. driverconnectionprovider"/>
<Add key = "hibernate. Connection. connection_string" value = "Server = (local); uid = sa; Pwd = 123456; database = test"/>
<Add key = "hibernate. show_ SQL" value = "true"/>
</Config>
</Activerecord>

1. Create

Create completes object-type storage operations by calling the nhib.pdf. isession. Save () method. After the method is called, we can immediately obtain the primarykey ID. User user = new user ();
User. Name = "user ";
User. Create ();

Console. writeline (user. ID );

SQL

Nhibes: insert into users (name) values (@ P0); select scope_identity ()
@ P0 = 'user'

2. Update

Update: Call the nhib.pdf. isession. Update () method to update the object type. User user2 = user. Find (1 );
User2.name = "user2 ";
User2.update ();

SQL

Nhib.pdf: Select user0 _. ID as id0 _, user0 _. Name as name0 _ from users user0 _ Where user0 _. ID = @ P0
@ P0 = '1'
Nhibers: Update users set name = @ P0 where id = @ p1
@ P0 = 'user2'
@ P1 = '1'

Most of the time, we first get the instance from the database and then update it. However, you can also directly create an object and update the value assignment. // First change the object above to ID {Get; set ;}
User user2 = new user ();
User2.id = 1;
User2.name = "ABCD ";
User2.update ();

SQL

Nhibers: Update users set name = @ P0 where id = @ p1
@ P0 = 'abc'
@ P1 = '1'

Compared with the SQL statements generated twice, the latter method is faster. However, the premise of updating is that you must know the "value" of all object attributes. This is usually not possible, so it is of little use.

3. Save

The Save method is interesting. It calls nhib.pdf. isession. saveorupdate (). That is to say, if it is a "new" object, it will create, otherwise update. User user = new user ();
User. Name = "user ";
User. Save ();

Console. writeline (user. ID );

User user2 = user. Find (user. ID );
User2.name = "user2 ";
User2.save ();

Console. writeline (user. Find (user. ID). Name );

SQL

Nhibes: insert into users (name) values (@ P0); select scope_identity ()
@ P0 = 'user'
Nhib.pdf: Select user0 _. ID as id0 _, user0 _. Name as name0 _ from users user0 _ Where user0 _. ID = @ P0
@ P0 = '1'
Nhibers: Update users set name = @ P0 where id = @ p1
@ P0 = 'user2'
@ P1 = '1'
Nhib.pdf: Select user0 _. ID as id0 _, user0 _. Name as name0 _ from users user0 _ Where user0 _. ID = @ P0
@ P0 = '1'

4. Delete

It is easier to delete objects. User user = new user ();
User. Name = "user ";
User. Save ();

User. Delete ();

SQL

Nhibernate: delete from users where id = @ P0
@ P0 = '1'

Ah ~~~ Deleteall remains the same. If you want to delete 10 million Entity Data, I strongly recommend that you have a cup of tea first. For (INT I = 0; I <10; I ++)
{
User user = new user ();
User. Name = "user" + I;
User. Save ();
}

User. deleteall ();

SQL

Nhib.pdf: Select user0 _. ID as ID, user0 _. Name as name from users user0 _
Nhibernate: delete from users where id = @ P0
@ P0 = '1'
Nhibernate: delete from users where id = @ P0
@ P0 = '2'
Nhibernate: delete from users where id = @ P0
@ P0 = '3'
Nhibernate: delete from users where id = @ P0
@ P0 = '4'
Nhibernate: delete from users where id = @ P0
@ P0 = '5'
Nhibernate: delete from users where id = @ P0
@ P0 = '6'
Nhibernate: delete from users where id = @ P0
@ P0 = '7'
Nhibernate: delete from users where id = @ P0
@ P0 = '8'
Nhibernate: delete from users where id = @ P0
@ P0 = '9'
Nhibernate: delete from users where id = @ P0
@ P0 = '10'

Deleteall also supports collection deletion. List <user> Users = new list <user> ();

For (INT I = 0; I <10; I ++)
{
User user = new user ();
User. Name = "user" + I;
User. Save ();

Users. Add (User );
}

User. deleteall (New int [] {users [1]. ID, users [3]. ID });

SQL

Nhib.pdf: Select user0 _. ID as id0 _, user0 _. Name as name0 _ from users user0 _ Where user0 _. ID = @ P0
@ P0 = '2'
Nhibernate: delete from users where id = @ P0
@ P0 = '2'
Nhib.pdf: Select user0 _. ID as id0 _, user0 _. Name as name0 _ from users user0 _ Where user0 _. ID = @ P0
@ P0 = '4'
Nhibernate: delete from users where id = @ P0
@ P0 = '4'

5. Refresh

Refresh is used to refresh entity information from the database. User user = new user ();
User. Name = "user ";
User. Save ();

User user2 = user. Find (user. ID );
User2.name = "XXXX ";
User2.save ();

Console. writeline (user. Name );
User. Refresh ();
Console. writeline (user. Name );

SQL

Nhib.pdf: Select user0 _. ID as id0 _, user0 _. Name as name0 _ from users user0 _ Where user0 _. ID = @ P0
@ P0 = '1'

6. Find

Ar provides multiple find methods to find objects.

(1) primarykey

For (INT I = 0; I <10; I ++)
{
User user = new user ();
User. Name = "user" + I;
User. Save ();
}

User u = user. Find (3 );
Console. writeline (U. Name );

We can also use tryfind instead of find. This method does not trigger an exception when no entity is found. User u = user. tryfind (500 );
Console. writeline (u = NULL );

(2) Property

For (INT I = 0; I <10; I ++)
{
User user = new user ();
User. Name = "user" + I;
User. Save ();
}

User [] US = user. findallbyproperty ("name", "user3 ");
Foreach (User U in US) console. writeline (U. Name );

(3) nhib.pdf. expression. icriterion

Nhib1_criterion is another "representation" of hql and can be used to combine multiple conditions. Commonly used include ltexpression (<), geexpression (> =), eqexpression (=), gtexpression (>), leexpression (<=), likeexpression, andexpression, betweenexpression, notexpression, notnullexpression, and nullexpression. You can also use nhib.pdf. Express. Order for sorting. For (INT I = 0; I <10; I ++)
{
User user = new user ();
User. Name = "user" + I;
User. Save ();
}

// User [] users = user. findall (New Order [] {New Order ("ID", false)}, new inexpression ("ID", new object [] {1, 3, 5 }));
// User [] users = user. findall (New eqexpression ("name", "user3 "));
// User [] users = user. findall (New orexpression (New eqexpression ("name", "user1"), new eqexpression ("name", "user3 ")));

// User u = user. findfirst (New betweenexpression ("ID", 3, 6 ));
User u = user. findone (New eqexpression ("ID", 3 ));

Note the difference between findone and findfirst. If the record returned by the expression exceeds 1, findone triggers an exception.

7. exists

Exists can be used to determine whether the corresponding data table has been created for the object type. You can also use the primary key to determine whether the object exists, or use the hql statement to make complex judgments. // Determine whether a data table exists
Console. writeline (user. exists ());

// Judge by primary key
Console. writeline (user. exists <int> (3 ));

// Hql
Console. writeline (user. exists ("name =? "," User3 "));
Console. writeline (user. exists ("name =? Or Id =? "," User400 ", 4 ));

8. Query

The biggest difference between query and find is its support for hql. Ar provides three query objects: simplequery, scalarquery, and countquery.

Simplequery: Used to obtain a set of information, such as an object array and a single attribute array.

For (INT I = 0; I <10; I ++)
{
User user = new user ();
User. Name = "user" + I;
User. Save ();
}

// Simplequery query = new simplequery (typeof (user), "from user where user. Name =? "," User2 ");
// User [] users = (User []) user. executequery (query );

// Simplequery query = new simplequery (typeof (user), typeof (string), "Select User. name from user where user. Name =? "," User2 ");
// String [] names = (string []) user. executequery (query );

// Simplequery <user> query = new simplequery <user> ("from user where user. Name =? "," User2 ");
// User [] users = query. Execute ();

Simplequery <string> query = new simplequery <string> (typeof (user), "Select User. name from user where user. Name =? "," User2 ");
String [] names = query. Execute ();

Scalarquery: Used to obtain a single object or multiple attributes of a single object. An exception is triggered when the number of returned OBJECT records is greater than 1.

For (INT I = 0; I <10; I ++)
{
User user = new user ();
User. Name = "user" + I;
User. Save ();
}

// Scalarquery query = new scalarquery (typeof (user), "from user where user. Name =? "," User2 ");
// User u = (User) user. executequery (query );

// Scalarquery query = new scalarquery (typeof (user), "Select User. ID, user. name from user where user. Name =? "," User2 ");
// Object [] properties = (object []) user. executequery (query );

// Scalarquery <user> query = new scalarquery <user> (typeof (user), "from user where user. Name =? "," User2 ");
// User u = query. Execute ();

Scalarquery <Object> query = new scalarquery <Object> (typeof (user), "Select User. ID, user. name from user where user. Name =? "," User2 ");
Object properties = query. Execute ();

Countquery: Used to count the number of entity records in the database.

// Countquery query = new countquery (typeof (User ));
// Console. writeline (user. executequery (query ));

Countquery query = new countquery (typeof (user), "name like? "," User1 % ");
Console. writeline (user. executequery (query ));

We can also use the querylanguage parameter in the overload method to directly execute SQL statements. However, we should use it with caution because it may lose the ability to switch databases freely.

9. Paging

Using countquery and activerecordbase. slicedfindall (), we can implement the paging query function. For (INT I = 1; I <= 100; I ++)
{
User user = new user ();
User. Name = "user" + I. tostring (). padleft (3, '0 ');
User. Save ();
}

Int pageindex = 5;
Int pagesize = 10;

Countquery = new countquery (typeof (user), "id <? ", 45 );
Int COUNT = (INT) user. executequery (countquery );

If (count> 0)
{
Int pagecount = count/pagesize + (count % pagesize> 0? 1: 0 );
Pageindex = math. Min (pageindex, pagecount );
Int first = math. Max (pageindex-1) * pagesize, 0 );

User [] users = user. slicedfindall (first, pagesize, new ltexpression ("ID", 45 ));
Foreach (User U in users) console. writeline (U. Name );
}

SQL

Nhibib: select count (*) as x0_0 _ from users user0 _ Where (ID <@ P0)
@ P0 = '45'
Nhib_: Select top 50 this. ID as id0 _, this. Name as name0 _ from users this where this. ID <@ P0
@ P0 = '45'

Looking at the SQL statements it generates, we can see that the efficiency is not very good. I just don't know whether the limit statement will be used for paging when SQLite/MySQL is used. Study ......

[Last modified by Yuanyuan, at 13:45:15,]

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.