如何结合多个表并使用Nhibernate在DB中执行分页

时间:2014-05-17 02:42:36

标签: sql nhibernate union paging

有没有办法在DB中实现联合和分页?

例如:

(select A.col1 As ColumnA, A.col2 as ColumnB, A.col3 as ColumnC from table1 as A)
union
(select B.col1 as ColumnA, B.col2 as ColumnB, B.col3 as ColumnC from table2 as B)

我找到了几种实现此功能的解决方案,但是分页是在内存中执行的,而不是在DB中执行的。

1 个答案:

答案 0 :(得分:1)

1。使用SQL查询

这有几个缺点,最明显的一点是LIMIT和OFFSET没有标准化 跨数据库(Oracle甚至需要子查询) - 因此,如果更改数据库,则还需要更改查询。

// PetDso is not NHibernate mapped, no virtual..
public class PetDto
{
  public string Name { get; set; }
  public string Owner { get; set; }
  public long Age { get; set; }
}

IList<PetDto> pets = session.CreateSQLQuery(@"
      select NAME as Name, OWNER as Owner, AGE as Age from CAT 
      union 
      select DOG_NAME as Name, OWNER_NAME as Owner, AGE_IN_YEARS as Age from DOG 
      order by Name, Owner, Age LIMIT :returnedRows OFFSET :skipRows")
    .SetParameter("skipRows", 1)
    .SetParameter("returnedRows", 2)
    .SetResultTransformer(new AliasToBeanResultTransformer(typeof(PetDto)))
    .List<PetDto>();

2。使用视图并映射它

在db中创建一个视图并映射它(可能使用&lt; class mutable =&#34; false&#34;&gt;)。但请注意,在查询之间不会发生变化的每一行都需要一个id,因为NH使用id缓存实体。


HQL不支持联合(NH-2710),它应该是查询db的最完整方式。