Select columns from join table only without requiring a join

Posted by Kent Boogaart on Stack Overflow See other posts from Stack Overflow or by Kent Boogaart
Published on 2010-03-22T10:04:42Z Indexed on 2010/03/22 11:41 UTC
Read the original article Hit count: 251

Filed under:
|
|
|

Given these tables:

create table Orders (
   Id INT IDENTITY NOT NULL,
   primary key (Id)
)

create table Items (
   Id INT IDENTITY NOT NULL,
   primary key (Id)
)

create table OrdersItems (
   OrderId INT not null,
   ItemId INT not null,
   primary key (OrderId, ItemId)
)

Is it possible to use HQL/criteria API to contruct a query that results in the following SQL:

SELECT
    [OrderId], [ItemId]
FROM
    [OrdersItems]

I've tried both of these approaches:

var hqlResults = session
    .CreateQuery("select order.id, item.id from Order order inner join order.Items item")
    .List();

var criteriaResults = session
    .CreateCriteria<Order>()
    .CreateAlias("Items", "item", NHibernate.SqlCommand.JoinType.None)
    .SetProjection(Projections.Property("id"), Projections.Property("item.id"))
    .List();

But both approaches insist on generating a join (or fail because the join isn't present, in using criteria), resulting in SQL such as:

select order.Id,
       item.Id
from   Orders order
       inner join OrdersItems ordersItems
         on order.Id = ordersItems.ArticleId
       inner join Items item
         on ordersItems.CategoryId = item.Id

Is there any way to have NHibernate generate a query that selects columns only from the join table, without requiring a join?

© Stack Overflow or respective owner

Related posts about nhibernate

Related posts about sql