【问题标题】:How to union multiple tables and perform paging in DB with Nhibernate如何使用 Nhibernate 合并多个表并在 DB 中执行分页
【发布时间】:2014-05-18 07:08:01
【问题描述】:

有没有办法在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 中。

【问题讨论】:

    标签: sql nhibernate union paging


    【解决方案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 中创建一个视图并映射它(可能使用 )。但请注意,您需要为每一行设置一个不会在查询之间更改的 id,因为 NH 正在使用 id 缓存实体。


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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-01
      • 2019-10-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多