Содержание

Слайд 2

Методы загрузки данных

SQL query
HQL query
Criteria query
QueryOver
LINQ to NHibernate

Методы загрузки данных SQL query HQL query Criteria query QueryOver LINQ to NHibernate

Слайд 4

Scalar queries

ISession session = DbSessionFactory.Instance.OpenSession();
ISQLQuery query = session.CreateSQLQuery("SELECT * FROM CATS")

Scalar queries ISession session = DbSessionFactory.Instance.OpenSession(); ISQLQuery query = session.CreateSQLQuery("SELECT * FROM
.AddScalar("ID", NHibernateUtil.Int64)
.AddScalar("NAME", NHibernateUtil.String)
.AddScalar("BIRTHDATE", NHibernateUtil.Date);
IList results = query.List();
Output:
object[] result = new object[3];
result = (object[])results[0];
long id = (long)result[0];
string name = (string)result[1];
DateTime birthdate = (DateTime)result[2];

Слайд 5

Entity queries

ISQLQuery query = session.CreateSQLQuery("SELECT * FROM CATS")
.AddEntity(typeof(Cat));
ISQLQuery query = session.CreateSQLQuery(@"SELECT ID,

Entity queries ISQLQuery query = session.CreateSQLQuery("SELECT * FROM CATS") .AddEntity(typeof(Cat)); ISQLQuery query
NAME,
BIRTHDATE FROM CATS")
.AddEntity(typeof(Cat));
IList results = query.List();
Output:
Cat cat = results[0] as Cat;

Слайд 6

Returning non-managed entities

session.CreateSQLQuery("SELECT NAME, BIRTHDATE FROM CATS")
.SetResultTransformer(Transformers.AliasToBean(typeof (CatDTO)));

Returning non-managed entities session.CreateSQLQuery("SELECT NAME, BIRTHDATE FROM CATS") .SetResultTransformer(Transformers.AliasToBean(typeof (CatDTO)));

Слайд 7

Named SQL queries



SELECT person.NAME AS {person.Name},
person.AGE

Named SQL queries SELECT person.NAME AS {person.Name}, person.AGE AS {person.Age}, person.SEX AS
AS {person.Age},
person.SEX AS {person.Sex}
FROM PERSON person
WHERE person.NAME LIKE :namePattern

IList people = session.GetNamedQuery("persons")
.SetString("namePattern", "smith")
.SetMaxResults(50)
.List();

Слайд 8

Named SQL queries




SELECT p.NAME

Named SQL queries SELECT p.NAME AS name, p.AGE AS age, FROM PERSON
AS name,
p.AGE AS age,
FROM PERSON p WHERE p.NAME LIKE 'Hiber%'

Слайд 9

Named SQL queries




Named SQL queries SELECT person.NAME AS myName, person.AGE AS myAge, person.SEX AS
column="myAge"/>


SELECT person.NAME AS myName,
person.AGE AS myAge,
person.SEX AS mySex,
FROM PERSON person WHERE person.NAME LIKE :name

Слайд 10

Using stored procedures for querying

CREATE PROCEDURE selectAllEmployments AS
SELECT EMPLOYEE, EMPLOYER, STARTDATE,

Using stored procedures for querying CREATE PROCEDURE selectAllEmployments AS SELECT EMPLOYEE, EMPLOYER,
ENDDATE,
REGIONCODE, EMPID, VALUE
FROM EMPLOYMENT

Слайд 11

Using stored procedures for querying




Using stored procedures for querying exec selectAllEmployments






exec selectAllEmployments

Слайд 12

Custom SQL for create/update/delete





Custom SQL for create/update/delete INSERT INTO PERSON (NAME, ID) VALUES ( UPPER(?),
not-null="true"/>
INSERT INTO PERSON (NAME, ID) VALUES ( UPPER(?), ? )
UPDATE PERSON SET NAME=UPPER(?) WHERE ID=?
DELETE FROM PERSON WHERE ID=?

Слайд 13

Stored procedures for create/update/delete





Stored procedures for create/update/delete exec createPerson ?, ? exec deletePerson ? exec updatePerson ?, ?
not-null="true"/>
exec createPerson ?, ?
exec deletePerson ?
exec updatePerson ?, ?

Слайд 14

Custom SQL for loading





Custom SQL for loading SELECT NAME AS {pers.Name}, ID AS {pers.Id} FROM
not-null="true"/>




SELECT NAME AS {pers.Name}, ID AS {pers.Id}
FROM PERSON
WHERE ID=?
FOR UPDATE

Слайд 16

Scalar and entity queries

string hql = "from Product p";
var products = session.CreateQuery(hql).List();
var

Scalar and entity queries string hql = "from Product p"; var products
products = session.CreateQuery(hql).List();

Слайд 17

Filtering, sorting and paging

string hql = @"from Product p
where p.Discontinued
and

Filtering, sorting and paging string hql = @"from Product p where p.Discontinued
p.Category = :category
and p.UnitPrice <= :unitPrice
order by p.Name";
var cheapFruits = session
.CreateQuery(hql)
.SetString("category", "Fruits")
.SetDecimal("unitPrice", 1.0m)
.SetFirstResult(10)
.SetMaxResults(10)
.List();

Слайд 18

Unique result

IQuery query = session.CreateQuery("select count(*) from Product");
int count = Convert.ToInt32(query.UniqueResult());
int count

Unique result IQuery query = session.CreateQuery("select count(*) from Product"); int count =
= query.UniqueResult();

Слайд 19

Result transformers

var productsLookup = session
.CreateQuery("select Id as Id, Name as Name

Result transformers var productsLookup = session .CreateQuery("select Id as Id, Name as
from Product")
.SetResultTransformer(Transformers.AliasToBean())
.List();

Слайд 20

Grouping

var productsGrouped = session
.CreateQuery(@"select p.Category as Category,
count(*) as Count,
avg(p.UnitPrice)

Grouping var productsGrouped = session .CreateQuery(@"select p.Category as Category, count(*) as Count,
as AveragePrice
from Product p
group by p.Category")
.List();

Слайд 21

Grouping with transformers

var productsGrouped = session
.CreateQuery(@"select p.Category as Category,
count(*) as

Grouping with transformers var productsGrouped = session .CreateQuery(@"select p.Category as Category, count(*)
Count,
avg(p.UnitPrice) as AveragePrice
from Product p
group by p.Category")
.SetResultTransformer(Transformers.AliasToEntityMap)
.List()
.Select(r => new
{
Category = r["Category"],
Count = r["Count"],
AveragePrice = r["AveragePrice"],
});

Слайд 22

Join

var products = session
.CreateQuery(@"select p from Product p
left join p.Category

Join var products = session .CreateQuery(@"select p from Product p left join
as c
left join c.Type t
where t.Name = 'Fruits'")
.List();
var hql = @"select p from Person as p
left join fetch p.Hobbies as h";
var listOfPersons = session.CreateQuery(hql)
.List();

Слайд 23

Multi query

public void GetPageOfProducts(int pageNumber, int pageSize)
{
ISession session = DbSessionFactory.Instance.OpenSession();
int

Multi query public void GetPageOfProducts(int pageNumber, int pageSize) { ISession session =
skip = (pageNumber - 1)*pageSize;
string countHql = @"select count(p.Id) from Product p";
IQuery countQuery = session.CreateQuery(countHql);
var productHql = @"from Product p order by p.UnitPrice asc";
IQuery resultQuery = session.CreateQuery(productHql)
.SetFirstResult(skip)
.SetMaxResults(pageSize);
IMultiQuery multiQuery = session.CreateMultiQuery()
.Add("count", countQuery)
.Add("page", resultQuery);
long productCount = ((IList) multiQuery.GetResult("count")).Single();
IList products = (IList) multiQuery.GetResult("page");
}

Слайд 24

Named queries


select count(p.Id) from Product p
]]>


Named queries select count(p.Id) from Product p ]]> from Product p order by p.UnitPrice asc ]]>
from Product p order by p.UnitPrice asc
]]>

Слайд 25

Named queries & futures

public void GetPageOfProducts(int pageNumber, int pageSize)
{
ISession session =

Named queries & futures public void GetPageOfProducts(int pageNumber, int pageSize) { ISession
DbSessionFactory.Instance.OpenSession();
var skip = (pageNumber - 1)*pageSize;
var productCount = session.GetNamedQuery("CountAllProducts")
.FutureValue();
var products = session.GetNamedQuery("GetAllProducts")
.SetFirstResult(skip)
.SetMaxResults(pageSize)
.Future();
var pageCount = (int) Math.Ceiling(
productCount.Value/(double) pageSize);
}

Слайд 26

Detached query

string hql = @"from Product p where p.Discontinued";
IDetachedQuery detachedQuery = new

Detached query string hql = @"from Product p where p.Discontinued"; IDetachedQuery detachedQuery
DetachedQuery(hql);
IQuery executableQuery = detachedQuery.GetExecutableQuery(session);
IList result = executableQuery.List();

Слайд 27

Bulk data changes

var updateHql = "update Product p set p.UnitPrice = 1.1

Bulk data changes var updateHql = "update Product p set p.UnitPrice =
* p.UnitPrice";
session.CreateQuery(updateHql).ExecuteUpdate();
var deleteHql = "delete Product p where p.Discontinued = true";
session.CreateQuery(deleteHql).ExecuteUpdate();
var insertHql = @"insert into Product(Id, Name, Category, UnitPrice)
select t.Id, t.Name, t.Category, t.UnitPrice
from ProductTemp t";
session.CreateQuery(insertHql).ExecuteUpdate();

Слайд 29

Restrictions

List products = session.CreateCriteria()
.Add(Restrictions.Eq("Name", productName))
.AddOrder(Order.Asc("UnitPrice"))
.List();

Restrictions List products = session.CreateCriteria () .Add(Restrictions.Eq("Name", productName)) .AddOrder(Order.Asc("UnitPrice")) .List ();

Слайд 30

Restrictions

Eq, EqProperty
Ge, Gt, GeProperty, GtProperty
Le, Lt, LeProperty, LtProperty
Like
In
Between
Not
IsNull
IsNotNull
Where
And
Or

Restrictions Eq, EqProperty Ge, Gt, GeProperty, GtProperty Le, Lt, LeProperty, LtProperty Like

Слайд 31

Restrictions

List products = session.CreateCriteria()
.Add(Restrictions.And(
Restrictions.Ge("UnitPrice", minPrice),
Restrictions.Le("UnitPrice", maxPrice)
))
.AddOrder(Order.Asc("UnitPrice"))
.List();

Restrictions List products = session.CreateCriteria () .Add(Restrictions.And( Restrictions.Ge("UnitPrice", minPrice), Restrictions.Le("UnitPrice", maxPrice) )) .AddOrder(Order.Asc("UnitPrice")) .List ();

Слайд 32

Join

IList categories = session.CreateCriteria()
.CreateCriteria("Products", JoinType.InnerJoin)
.Add(Restrictions.Eq("Discount", 0))
.List();

Join IList categories = session.CreateCriteria () .CreateCriteria("Products", JoinType.InnerJoin) .Add(Restrictions.Eq("Discount", 0)) .List ();

Слайд 33

Paging

List products = session.CreateCriteria()
.Add(Restrictions.Eq("Name", productName))
.SetFirstResult(10)
.SetMaxResults(10)
.List();

Paging List products = session.CreateCriteria () .Add(Restrictions.Eq("Name", productName)) .SetFirstResult(10) .SetMaxResults(10) .List ();

Слайд 34

Projections

IList products = session.CreateCriteria()
.Add(Restrictions.Eq("Name", productName))
.SetProjection(Projections.ProjectionList()
.Add(Projections.Property("Id"))
.Add(Projections.Property("Name")))
.SetResultTransformer(Transformers.AliasToBean(typeof(NameID)))
.List();

Projections IList products = session.CreateCriteria () .Add(Restrictions.Eq("Name", productName)) .SetProjection(Projections.ProjectionList() .Add(Projections.Property("Id")) .Add(Projections.Property("Name"))) .SetResultTransformer(Transformers.AliasToBean(typeof(NameID))) .List();

Слайд 35

Aggregate functions

var productCount = session.CreateCriteria()
.Add(Restrictions.Eq("Name", productName))
.SetProjection(Projections.RowCount())
.UniqueResult();

Aggregate functions var productCount = session.CreateCriteria () .Add(Restrictions.Eq("Name", productName)) .SetProjection(Projections.RowCount()) .UniqueResult();

Слайд 36

Multi criteria

public void GetPageOfProducts(int pageNumber, int pageSize)
{
ISession session = DbSessionFactory.Instance.OpenSession();
int

Multi criteria public void GetPageOfProducts(int pageNumber, int pageSize) { ISession session =
skip = (pageNumber - 1) * pageSize;
ICriteria rowCount = session.CreateCriteria(typeof(Product))
.SetProjection(Projections.Count(Projections.Id()));
ICriteria criteria = session.CreateCriteria(typeof(Product))
.Add(Restrictions.Gt("UnitPrice", 0))
.AddOrder(Order.Asc("UnitPrice"))
.SetFirstResult(skip)
.SetMaxResults(pageSize);
IMultiCriteria multiCriteria = session.CreateMultiCriteria()
.Add("count", rowCount)
.Add("page", criteria);
long productCount = ((IList)multiCriteria.GetResult("count")).Single();
IList products = (IList)multiCriteria.GetResult("page");
}

Слайд 37

Detached criteria

DetachedCriteria detachedCriteria = DetachedCriteria.For()
.Add(Restrictions.Like("Name", productName));
IList results = detachedCriteria.GetExecutableCriteria(session).List();

Detached criteria DetachedCriteria detachedCriteria = DetachedCriteria.For () .Add(Restrictions.Like("Name", productName)); IList results = detachedCriteria.GetExecutableCriteria(session).List();

Слайд 38

QueryOver

QueryOver

Слайд 39

QueryOver

IList results = session.QueryOver()
.Where(x => x.ProductType == ProductTypes.ProductTypeA)
.OrderBy(x => x.Name)

QueryOver IList results = session.QueryOver () .Where(x => x.ProductType == ProductTypes.ProductTypeA) .OrderBy(x => x.Name) .Desc .List();
.Desc
.List();

Слайд 40

QueryOver

IList results = session.QueryOver()
.WhereRestrictionOn(x => x.UnitPrice)
.IsBetween(20).And(50)
.OrderBy(x => x.Name)
.Desc

QueryOver IList results = session.QueryOver () .WhereRestrictionOn(x => x.UnitPrice) .IsBetween(20).And(50) .OrderBy(x => x.Name) .Desc .List();
.List();

Слайд 41

QueryOver

IList results = session.QueryOver()
.Select(m => m.Name, m => m.UnitPrice)
.List()
.Select(props

QueryOver IList results = session.QueryOver () .Select(m => m.Name, m => m.UnitPrice)
=>
new NamePrice()
{
Name = (string) props[0],
Price = (decimal) props[1]
});

Слайд 42

Projections

var result = session.QueryOver()
.Select(Projections.Avg(m => m.UnitPrice))
.SingleOrDefault();

Projections var result = session.QueryOver () .Select(Projections.Avg (m => m.UnitPrice)) .SingleOrDefault ();

Слайд 43

Join, paging

IList categories = session.QueryOver()
.Inner.JoinQueryOver(x => x.Products)
.Skip(20)
.Take(10)
.List();

Join, paging IList categories = session.QueryOver () .Inner.JoinQueryOver(x => x.Products) .Skip(20) .Take(10) .List ();

Слайд 44

Session methods

Session methods

Слайд 45

Session actions

using (ISession session = DbSessionFactory.Instance.OpenSession())
{
using (ITransaction transaction = session.BeginTransaction())
{

Session actions using (ISession session = DbSessionFactory.Instance.OpenSession()) { using (ITransaction transaction =
// create, update, delete, or read data
transaction.Commit();
}
}

Слайд 46

Session methods

Insert
Save
Update
SaveOrUpdate
Delete
Get
Load
Merge
Flush
Refresh
Evict
Clear
Close

Session methods Insert Save Update SaveOrUpdate Delete Get Load Merge Flush Refresh Evict Clear Close
Имя файла: NHibernate-.pptx
Количество просмотров: 170
Количество скачиваний: 0