Programming

NHibernate로 어떻게 페이징을 할 수 있습니까?

procodes 2020. 8. 8. 14:06
반응형

NHibernate로 어떻게 페이징을 할 수 있습니까?


예를 들어, 표시된 행 수에 필요한 데이터 만 사용하여 ASP.NET 웹 페이지에서 gridview 컨트롤을 채우려 고합니다. NHibernate는 이것을 어떻게 지원할 수 있습니까?


ICriteriaSetFirstResult(int i)당신이 얻을하고자하는 첫 번째 항목의 인덱스 (페이지에서 기본적으로 첫 번째 데이터 행) 표시 방법.

또한 SetMaxResults(int i)가져 오려는 행 수 (예 : 페이지 크기)를 나타내는 메서드 도 있습니다 .

예를 들어이 기준 객체는 데이터 그리드의 처음 10 개 결과를 가져옵니다.

criteria.SetFirstResult(0).SetMaxResults(10);

또한 NHibernate의 Futures 기능을 이용하여 쿼리를 실행하여 단일 쿼리의 실제 결과뿐만 아니라 총 레코드 수를 얻을 수도 있습니다.

 // Get the total row count in the database.
var rowCount = this.Session.CreateCriteria(typeof(EventLogEntry))
    .Add(Expression.Between("Timestamp", startDate, endDate))
    .SetProjection(Projections.RowCount()).FutureValue<Int32>();

// Get the actual log entries, respecting the paging.
var results = this.Session.CreateCriteria(typeof(EventLogEntry))
    .Add(Expression.Between("Timestamp", startDate, endDate))
    .SetFirstResult(pageIndex * pageSize)
    .SetMaxResults(pageSize)
    .Future<EventLogEntry>();

총 레코드 수를 얻으려면 다음을 수행하십시오.

int iRowCount = rowCount.Value;

Futures가 제공하는 것에 대한 좋은 토론이 여기에 있습니다 .


NHibernate 3 이상에서 다음을 사용할 수 있습니다 QueryOver<T>.

var pageRecords = nhSession.QueryOver<TEntity>()
            .Skip((PageNumber - 1) * PageSize)
            .Take(PageSize)
            .List();

다음과 같이 결과를 명시 적으로 정렬 할 수도 있습니다.

var pageRecords = nhSession.QueryOver<TEntity>()
            .OrderBy(t => t.AnOrderFieldLikeDate).Desc
            .Skip((PageNumber - 1) * PageSize)
            .Take(PageSize)
            .List();

public IList<Customer> GetPagedData(int page, int pageSize, out long count)
        {
            try
            {
                var all = new List<Customer>();

                ISession s = NHibernateHttpModule.CurrentSession;
                IList results = s.CreateMultiCriteria()
                                    .Add(s.CreateCriteria(typeof(Customer)).SetFirstResult(page * pageSize).SetMaxResults(pageSize))
                                    .Add(s.CreateCriteria(typeof(Customer)).SetProjection(Projections.RowCountInt64()))
                                    .List();

                foreach (var o in (IList)results[0])
                    all.Add((Customer)o);

                count = (long)((IList)results[1])[0];
                return all;
            }
            catch (Exception ex) { throw new Exception("GetPagedData Customer da hata", ex); }
      }

데이터를 페이징 할 때 MultiCriteria에서 형식화 된 결과를 얻는 또 다른 방법이 있습니까? 아니면 모든 사람이 저처럼 똑같이 수행합니까?

감사


Ayende 의이 블로그 게시물 에서 논의 된 것처럼 Linq를 NHibernate에 사용 하는 것은 어떻습니까?

코드 샘플 :

(from c in nwnd.Customers select c.CustomerID)
        .Skip(10).Take(10).ToList(); 

그리고 여기에 페이징 구현을 포함하여 NHibernate 를 사용한 데이터 액세스 에 대한 NHibernate 팀 블로그의 자세한 게시물이 있습니다.


대부분의 경우 GridView에서 데이터 조각과 쿼리와 일치하는 총 데이터 양의 총 행 수 (rowcount)를 표시하려고 할 것입니다.

MultiQuery를 사용하여 Select count (*) 쿼리와 .SetFirstResult (n) .SetMaxResult (m) 쿼리를 한 번의 호출로 데이터베이스에 보내야합니다.

Note the result will be a list that holds 2 lists, one for the data slice and one for the count.

Example:

IMultiQuery multiQuery = s.CreateMultiQuery()
    .Add(s.CreateQuery("from Item i where i.Id > ?")
            .SetInt32(0, 50).SetFirstResult(10))
    .Add(s.CreateQuery("select count(*) from Item i where i.Id > ?")
            .SetInt32(0, 50));
IList results = multiQuery.List();
IList items = (IList)results[0];
long count = (long)((IList)results[1])[0];

I suggest that you create a specific structure to deal with pagination. Something like (I'm a Java programmer, but that should be easy to map):

public class Page {

   private List results;
   private int pageSize;
   private int page;

   public Page(Query query, int page, int pageSize) {

       this.page = page;
       this.pageSize = pageSize;
       results = query.setFirstResult(page * pageSize)
           .setMaxResults(pageSize+1)
           .list();

   }

   public List getNextPage()

   public List getPreviousPage()

   public int getPageCount()

   public int getCurrentPage()

   public void setPageSize()

}

I didn't supply an implementation, but you could use the methods suggested by @Jon. Here's a good discussion for you to take a look.

참고URL : https://stackoverflow.com/questions/54754/how-can-you-do-paging-with-nhibernate

반응형