Hibernate Queries - III

3 May 2008

I will continue exploring Hibernate queries with example.

The exampel presented below returns the order id, number of items and total value of the order for all unpaid orders for a particular customer and given minimum total value, ordering the results by total value. It uses four inner joins and an (uncorrelated) subselect.

select order.id, sum(price.amount), count(item)
from Order as order
    join order.lineItems as item
    join item.product as product,
    Catalog as catalog
    join catalog.prices as price
where order.paid = false
    and order.customer = :customer
    and price.product = product
    and catalog.effectiveDate < sysdate
    and catalog.effectiveDate >= all (
        select cat.effectiveDate 
        from Catalog as cat
        where cat.effectiveDate < sysdate
    )
group by order
having sum(price.amount) > :minAmount
order by sum(price.amount) desc

The above query without subqueries in simplest form is:

select order.id, sum(price.amount), count(item)
from Order as order
    join order.lineItems as item
    join item.product as product,
    Catalog as catalog
    join catalog.prices as price
where order.paid = false
    and order.customer = :customer
    and price.product = product
    and catalog = :currentCatalog
group by order
having sum(price.amount) > :minAmount
order by sum(price.amount) desc

The next example counts the number of payments in each status, excluding all payments in the AWAITING_APPROVAL status where the most recent status change was made by the current user.

select count(payment), status.name 
from Payment as payment 
    join payment.currentStatus as status
    join payment.statusChanges as statusChange
where payment.status.name <> PaymentStatus.AWAITING_APPROVAL
    or (
        statusChange.timeStamp = ( 
            select max(change.timeStamp) 
            from PaymentStatusChange change 
            where change.payment = payment
        )
        and statusChange.user <> :currentUser
    )
group by status.name, status.sortOrder
order by status.sortOrder

del.icio.us:Hibernate Queries - III  digg:Hibernate Queries - III  spurl:Hibernate Queries - III  wists:Hibernate Queries - III  simpy:Hibernate Queries - III  newsvine:Hibernate Queries - III  blinklist:Hibernate Queries - III  furl:Hibernate Queries - III  reddit:Hibernate Queries - III  fark:Hibernate Queries - III  blogmarks:Hibernate Queries - III  Y!:Hibernate Queries - III  smarking:Hibernate Queries - III  magnolia:Hibernate Queries - III  segnalo:Hibernate Queries - III  gifttagging:Hibernate Queries - III

Top Of Page | Trackback

If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.

It will look like this: Hibernate Queries - III

Leave a Reply