NHibernate ICriteria多表一对多关联查询

配置文件

Customer.hbm.xml

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class name="Entity.CustomerEntity, Entity" table="Customer" lazy="false" >
    <id name="CustomerID" column="CustomerID" type="Int32">
      <generator class="identity" />
    </id>
    <property name="CustomerName" column="CustomerName" type="String" length="10" />
    <bag name="Files" table="File" cascade="all">
      <key column="FileID" foreign-key="FileID"></key>
      <one-to-many class="Entity.FileEntity, Entity"/>
    </bag>
  </class>
</hibernate-mapping>

File.hbm.xml

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class name="Entity.FileEntity, Entity" table="File1"  lazy="false">
    <id name="FileID" column="FileID" type="Int32">
      <generator class="identity" />
    </id>
    <property name="FileSize" column="FileSize" type="Int32" length="4" />
    <property name="CustomerID" column="CustomerID" type="Int32" length="4" />
    <many-to-one name="Customer" column="CustomerID" class="Entity.CustomerEntity, Entity" insert="false"/>
    <bag name="DownloadLogs" table="DownloadLog" cascade="all">
      <key column="FileID"/>
      <one-to-many class="Entity.DownloadLogEntity, Entity" />
    </bag>
  </class>
</hibernate-mapping>

DownloadLog.hbm.xml

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class name="Entity.DownloadLogEntity, Entity" table="DownloadLog" lazy="false" >
    <id name="DownloadLogID" column="DownloadLogID" type="Int32">
      <generator class="identity" />
    </id>
    <property name="FileID" column="FileID" type="Int32" length="4" />
    <property name="Times" column="Times" type="Int32" length="4" />
    <many-to-one name="File" column="FileID" class="Entity.FileEntity, Entity" insert="false"/>
  </class>
</hibernate-mapping>

从配置文件上可以看出
每个customer对应多个file,每个file对应多个downloadlog
如果使用icriteria查询customer对应的downloadlog
可以这样写:

public IList<DownloadLogEntity> GetByCustomerID(int customerID)
{
  ICriteria criteria = NHibernateSession.CreateCriteria(typeof(DownloadLogEntity));
  criteria.CreateAlias("File", "file");
  criteria.CreateAlias("file.Customer", "customer");
  criteria.Add(Expression.Eq("customer.CustomerID",customerID));
  return criteria.List<DownloadLogEntity>();
}

Nhibernate ICriteria sum字段求和

ICriteria criteria = NHibernateSession.CreateCriteria(typeof(DownloadLogEntity));
criteria.CreateAlias("Enduser", "enduser");
criteria.Add(Expression.Eq("enduser.EnduserID",enduserID));
criteria.Add(Expression.Between("DownloadTime", day, day.AddDays(1)));
criteria.SetProjection(Projections.Sum("FileSize"));
return (int)criteria.UniqueResult();

sql join inner join on, left join on, right join on讲解

1.理论

    只要两个表的公共字段有匹配值,就将这两个表中的记录组合起来。

    个人理解:以一个共同的字段求两个表中符合要求的交集,并将每个表符合要求的记录以共同的字段为牵引合并起来。


语法

FROM table1 INNER JOIN table2 ON table1 . field1 compopr table2 . field2

INNER JOIN 操作包含以下部分:

部分

说明

table1, table2

要组合其中的记录的表的名称。

field1field2

要联接的字段的名称。如果它们不是数字,则这些字段的数据类型必须相同,并且包含同类数据,但是,它们不必具有相同的名称。

compopr

任何关系比较运算符:“=”“<”“>”“<=”“>=”或者“<>”


说明

    可以在任何 FROM 子句中使用 INNER JOIN 操作。这是最常用的联接类型。只要两个表的公共字段上存在相匹配的值,Inner 联接就会组合这些表中的记录。

    可以将 INNER JOIN 用于 Departments Employees 表,以选择出每个部门的所有雇员。而要选择所有部分(即使某些部门中并没有被分配雇员)或者所有雇员(即使某些雇员没有分配到任何部门),则可以通过 LEFT JOIN 或者 RIGHT JOIN 操作来创建外部联接如果试图联接包含备注OLE 对象数据的字段,将发生错误。

    可以联接任何两个相似类型的数字字段。例如,可以联接自动编号长整型字段,因为它们均是相似类型。然而,不能联接单精度型双精度型类型字段。

    下例展示了如何通过 CategoryID 字段联接 Categories Products 表:

SELECT CategoryName, ProductName

FROM Categories INNER JOIN Products

ON Categories.CategoryID = Products.CategoryID;


在前面的示例中,CategoryID 是被联接字段,但是它不包含在查询输出中,因为它不包含在 SELECT 语句中。若要包含被联接字段,请在 SELECT 语句中包含该字段名,在本例中是指 Categories.CategoryID


也可以在 JOIN 语句中链接多个 ON 子句,请使用如下语法:

SELECT fields
FROM table1 INNER JOIN table2
ON table1.field1 compopr table2.field1 AND
ON table1.field2 compopr table2.field2) OR
ON table1.field3 compopr table2.field3)];


也可以通过如下语法嵌套 JOIN 语句:

SELECT fields
FROM table1 INNER JOIN
(table2 INNER JOIN [( ]table3
[INNER JOIN [( ]tablex [INNER JOIN …)]
ON table3.field3 compopr tablex.fieldx)]
ON table2.field2 compopr table3.field3)
ON table1.field1 compopr table2.field2;

LEFT JOIN RIGHT JOIN 可以嵌套在 INNER JOIN 之中,但是 INNER JOIN 不能嵌套于 LEFT JOIN RIGHT JOIN 之中。


2.
操作实例


A记录如下:

aID               aNum
1                  a20050111
2                  a20050112
3                  a20050113
4                  a20050114
5                  a20050115

B记录如下:
bID               bName

1                   2006032401
2                  2006032402
3                  2006032403
4                  2006032404
8                  2006032408

实验如下:
1.left join

sql语句如下:
select * from A
left join B
on A.aID = B.bID

结果如下:
aID               aNum                          bID                  bName
1                   a20050111                1                      2006032401
2                   a20050112                2                     2006032402
3                   a20050113                3                     2006032403
4                   a20050114                4                     2006032404
5                   a20050115                NULL              NULL
(所影响的行数为 5 行)

结果说明:
left join
是以A表的记录为基础的,A可以看成左表,B可以看成右表,left join是以左表为准的换句话说,左表(A)的记录将会全部表示出来,而右表(B)只会显示符合搜索条件的记录(例子中为: A.aID = B.bID)。B表记录不足的地方均为NULL.

2.right join
sql语句如下:
select * from A
right join B
on A.aID = B.bID
结果如下:
aID               aNum                          bID                  bName
1                   a20050111                1                      2006032401
2                   a20050112                2                     2006032402
3                   a20050113                3                     2006032403
4                   a20050114                4                     2006032404
NULL           NULL                          8                     2006032408
(所影响的行数为 5 行)


结果说明
:
仔细观察一下,就会发现,left join的结果刚好相反,这次是以右表(B)为基础的,A表不足的地方用NULL填充.


3.inner join
sql语句如下:
select * from A
innerjoin B
on A.aID = B.bID

结果如下:
aID               aNum                          bID                  bName
1                   a20050111                1                      2006032401
2                   a20050112                2                     2006032402
3                   a20050113                3                     2006032403
4                   a20050114                4                     2006032404

结果说明:
很明显,这里只显示出了 A.aID = B.bID的记录.这说明inner join并不以谁为基础,它只显示符合条件的记录.

group by time span

SELECT count(*),
DateAdd(second, -DatePart(second, clientTime) ,
DateAdd(ms, -DatePart(ms, clientTime), clientTime))
FROM dbo.V_COMBINED
WHERE (sessionId = '122b')
AND (type = N'sys_goodaction')
AND (paraName = 'value')
GROUP BY DateAdd(second, -DatePart(second, clientTime) % 5
,DateAdd(ms, -DatePart(ms, clientTime), clientTime))

group by time span 一个时间段

SELECT sum(sizeamount) as counts
,[ShopID]
,dateadd(hh, - datepart(hour,downloadtime) % 24 ,downloadtime)
FROM [abc].[dbo].[ShopDownloadAmount]
group by shopid, dateadd(hh, - datepart(hour,downloadtime) % 24 ,downloadtime)
order by dateadd(hh, - datepart(hour,downloadtime) % 24 ,downloadtime)

结果如下
36730    2    2009-12-15 00:00:00.000
72342    2    2009-12-16 00:00:00.000
76858    2    2009-12-17 00:00:00.000
34094    2    2009-12-18 00:00:00.000
58178    2    2009-12-19 00:00:00.000

存储过程

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[StoredProcedure1]
/*
(
@parameter1 int = 5,
@parameter2 datatype OUTPUT
)
*/
AS
declare @time datetime
set @time=DATEADD(hour, DATEDIFF(hour, 0, getdate()), 0) 
declare ShopAmount cursor for SELECT     SUM(dbo.DlsDownloadLog.MediaID) AS Expr1, dbo.Shop.ShopID
FROM         dbo.DlsDownloadLog INNER JOIN
dbo.EndUser ON dbo.DlsDownloadLog.EndUserID = dbo.EndUser.EndUserID INNER JOIN
dbo.Shop ON dbo.EndUser.ShopID = dbo.Shop.ShopID
WHERE     (dbo.DlsDownloadLog.DownloadDate > dateadd(hour,-1,@time)) AND (dbo.DlsDownloadLog.DownloadDate <= @time)
GROUP BY dbo.Shop.ShopID

declare @amount int, @shopid int
open ShopAmount
Fetch ShopAmount into @amount,@shopid
While (@@fetch_status=0)
Begin

insert into DlsShopDownloadAmount
(
ShopID,
Amount,
RecordTime
)
values
(
@shopid,
@amount,
@time
)

Fetch ShopAmount into @amount,@shopid
End
close ShopAmount
deallocate ShopAmount

RETURN

NHibernate??????sql°??±?????????á??×??????è??·????à?????????à??

public IList<ShopDownloadAmountEntity> GetDayByShopBetween(int shopID, DateTime startTime, DateTime endTime)
{
StringBuilder sb = new StringBuilder();
sb.Append("SELECT sum(sizeamount) as SizeAmount,[ShopID],");

sb.Append("dateadd(hh, – datepart(hour,downloadtime) % 24 ,downloadtime) as DownloadTime ");
sb.Append("FROM ShopDownloadAmount ");
sb.Append("WHERE downloadtime between ‘" + startTime + "’ and ‘" + endTime + "’");
sb.Append(" GROUP BY shopid, dateadd(hh, – datepart(hour,downloadtime) % 24 ,downloadtime) ");
sb.Append(" order by dateadd(hh, – datepart(hour,downloadtime) % 24 ,downloadtime)");//sql string

ISQLQuery sql = NHibernateSession.CreateSQLQuery(sb.ToString());
sql.AddScalar("SizeAmount", NHibernateUtil.Int32);//set type of data
sql.AddScalar("ShopID", NHibernateUtil.Int32);
sql.AddScalar("DownloadTime", NHibernateUtil.DateTime);
sql.SetResultTransformer(Transformers.AliasToBean(typeof(ShopDownloadAmountEntity)));//make the result set to entity
return sql.List<ShopDownloadAmountEntity>();
}
ShopDownloadAmountEntity???????à??SizeAmount??ShopID??DownloadTime??setter

automapper list

Mapper.CreateMap<Source, Destination>();
var sources = new[]
{
new Source {Value = 5},
new Source {Value = 6},
new Source {Value = 7}
};
IEnumerable<Destination> ienumerableDest = Mapper.Map<Source[], IEnumerable<Destination>>(sources);
ICollection<Destination> icollectionDest = Mapper.Map<Source[], ICollection<Destination>>(sources);
IList<Destination> ilistDest = Mapper.Map<Source[], IList<Destination>>(sources);
List<Destination> listDest = Mapper.Map<Source[], List<Destination>>(sources);
Destination[] arrayDest = Mapper.Map<Source[], Destination[]>(sources);

如果sources不是数组的话,可以调用ToArray<Destination>()转换一下