且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用多列对不同的select进行计数

更新时间:2023-02-02 22:42:24

好的找到了解决方案,我真正需要的只是在多列上使用不同的输出行计数已经被指定更好,我知道)。



感兴趣的解决方案:

  session.beginTransaction(); 
Criteria criteria = session.createCriteria(clazz);

ProjectionList p = Projections.projectionList();
p.add(Projections.property(supplierName));
p.add(Projections.property(supplierNr));
criteria.setProjection(Projections.distinct(p));

criteria.setResultTransformer(Transformers.TO_LIST);

ScrollableResults results = criteria.scroll();
results.last();
count = results.getRowNumber()+ 1;
results.close();
session.getTransaction()。commit();

其中有趣的部分是ScrollableResult并且没有使用DetachedCriteria。

I have been searching for some time but not found enough answers to do this myself.

I have an MsSQL that looks like this:

select count(*) from 
   ( select distinct supplierName, supplierNr
   from dbo.InvoiceTypeBean
   ) as a

This returns what I want using pure SQL

But i need this in hibernate using criteria and/or detachedcriteria:

The detached criteria part:

DetachedCriteria dCriteria = DetachedCriteria.forClass(clazz);
ProjectionList p = Projections.projectionList();
p.add(Projections.property("supplierName"));
p.add(Projections.property("supplierNr"));
dCriteria.setProjection(Projections.distinct(p));

The problem is attaching it to the criteria:

Criteria criteria = session.createCriteria(clazz);
.... Some atachement
criteria.setProjection(Projections.rowCount());
int count = ((Number) criteria.uniqueResult()).intValue();

I really need the solution to use Criteria and/or DetachedCriteria as the queries are being build dynamically, and a greater solution is build using them.

Well found the solution, what I really needed was just the row count of the output when using distinct on multiple columns (could have been specified better I know).

The solution for interested:

session.beginTransaction();
Criteria criteria = session.createCriteria(clazz);

ProjectionList p = Projections.projectionList();
p.add(Projections.property("supplierName"));
p.add(Projections.property("supplierNr"));
criteria.setProjection(Projections.distinct(p));

criteria.setResultTransformer(Transformers.TO_LIST);

ScrollableResults results = criteria.scroll();
results.last();
count = results.getRowNumber() + 1;
results.close();
session.getTransaction().commit();

Where the interesting part is the scrollableresult and no use of DetachedCriteria.