NHibernate使用入门(五)

时间:2022-08-16 08:22:58

CriteriaQuery和HQLQuery知识点

项目结构如图:

NHibernate使用入门(五)

Model类库如下

Customer.cs类和Customer.hbm.xml实体映射文件

[Serializable]
public class Customer
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }

public Address Address { get; set; }

public byte[] DbVersion { get; set; }
public int Version { get; set; }
public DateTime Timestamp { get; set; }

public IList<Order> Orders { get; set; }

public Customer()
{
Orders = new List<Order>();
}
}

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-lazy="false"
assembly="Ntest"
namespace="Ntest.Entities"
>

<class name="Customer">
<id type="int" name="Id">
<column name="Id" />
<generator class="identity"></generator>
</id>
<property name="FirstName"/>
<property name="LastName"/>

<bag name="Orders" cascade="all" lazy="true">
<key column="customerId"
not-null="true"/>

<one-to-many class="Order"/>
</bag>

</class>
</hibernate-mapping>

Order.cs类和Order.hbm.xml实体映射文件

[Serializable]
public class Order
{
public int Id { get; set; }
public decimal Value { get; set; }
public IList<Category> Categories { get; set; }

public Customer Customer { get; set; }

public Order()
{
Categories = new List<Category>();
}
}

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-lazy="false"
assembly="Ntest"
namespace="Ntest.Entities"
>

<class name="Order" table="Orders">
<id type="int" name="Id">
<column name="Id" />
<generator class="identity"></generator>
</id>
<property name="Value"/>

<many-to-one name="Customer" column="customerId" not-null="true"/>

</class>
</hibernate-mapping>

hibernate.cfg.xml全局映射文件

<?xml version="1.0" encoding="utf-8"?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string">Data Source=.\SQLINSTANCE;Initial Catalog=NHibernateDeepDive;Persist Security Info=True;User ID=sa;Password=123456</property>
<property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>

<property name="query.substitutions">true=1;false=0</property>
<!--<property name="show_sql">true</property>-->
<property name='proxyfactory.factory_class'>NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>

<!--设定映射文件默认所在的程序集。-->
<mapping assembly='Ntest' />
</session-factory>
</hibernate-configuration>

CriteriaQuery.cs查询类

 public class CriteriaQuery 
{
ISessionFactory sessionFactory = new Configuration().Configure().BuildSessionFactory();


public void SimpleQueries()
{
using (ISession session = sessionFactory.OpenSession())
{
var result = (int) session.CreateCriteria(typeof (Customer)).SetProjection(Projections.RowCount()).UniqueResult();

session.CreateCriteria(typeof (Customer))
.CreateCriteria("Orders", "o")
.Add(Restrictions.Gt("o.Value", 90m))
.List<Customer>();

session.CreateCriteria<Customer>()
.CreateCriteria("Orders", "o")
.SetProjection(Projections.RowCount())
.SetProjection(Projections.GroupProperty("LastName"))
.SetProjection(Projections.Max("o.Value"))
.List();

foreach (Customer customer in session.CreateCriteria<Customer>().List<Customer>())
{
int orderCound = customer.Orders.Count;
}

Console.WriteLine("SimpleQueries_CustomerCount:" + result);
}
}

// NHibernate3新出了新的查询API QueryOver。本节将为您介绍这查询API QueryOver的相关内容。
//QueryOver构建在NHibernate原有的ICriteria API之上,支持Lambda表达式与扩展方法。
public void QueryOver()
{
using (ISession session = sessionFactory.OpenSession())
{
int result = session.QueryOver<Customer>().RowCount();

IList<Customer> customers =
session.QueryOver<Customer>().JoinQueryOver<Order>(cust => cust.Orders).Where(
o => o.Value > 90).List<Customer>();

IList<object> results =
session.QueryOver<Customer>()
.SelectList(list =>
list.SelectGroup(c => c.LastName))
.JoinQueryOver<Order>(cust => cust.Orders).List<object>();
Console.WriteLine("QueryOver_CustomerCount:"+result);
}
}

}

HQLQuery.cs查询类

  public class HQLQuery
{
ISessionFactory sessionFactory = new Configuration().Configure().BuildSessionFactory();

public void SimpleQueries()
{
using (ISession session = sessionFactory.OpenSession())
{
long result = (long) session.CreateQuery("select count(*) from Customer").UniqueResult();
IList<Customer> customers =
session.CreateQuery("
select cust from Customer as cust inner join cust.Orders as order where order.Value > 90").List
<Customer>();

IList results = session.CreateQuery(
"
select cust.LastName, max(o.Value) from Customer as cust inner join cust.Orders as o group by cust.LastName").List();

Console.WriteLine("
HQLQuery_SimpleQueries:" + result);
}

}
}

主程序

class Program
{

static void Main(string[] args)
{
//CriteriaQuery query = new CriteriaQuery();
//query.SimpleQueries();
//query.QueryOver();
//---------------------------------------------------
HQLQuery hq=new HQLQuery();
hq.SimpleQueries();
Console.ReadKey();
}
}

运行结果

NHibernate使用入门(五)