3

I have a many-to-one relation mapped between two entities A and B. I will use Fruit and Color to simulate my scenario:

Assuming all the fruit has only one color. So I have a Color property in my Fruit class and in my mapping code for Fruit I have:

ManyToOne(f=>f.Color, mapper=>mapper.Column("ColorId"));

And the generated SQL has the following:

Select f0_.Name, f0...From Fruit f0_
  left outer join Color c0_
  on f0_.ColorId = c0_.id

I am wondering if there is any way for force an inner join instead of outer join. Because from the business perspective, a fruit without a color is not really a fruit and shouldn't exist.

rae1
  • 6,066
  • 4
  • 27
  • 48
Wei Ma
  • 3,125
  • 6
  • 44
  • 72

1 Answers1

2

Using Criteria API, we can achieve both left and/or inner join:

LEFT

// default left outer join
var leftResult = session.CreateCriteria<Fruit>()
  .SetFetchMode("Color", NHibernate.FetchMode.Join)
  .List<Fruit>();

INNER

// explicit inner join
var innerResult = session.CreateCriteria<Fruit>()
  .CreateCriteria("Color", NHibernate.SqlCommand.JoinType.InnerJoin)
  .List<Fruit>();

leftResult will contain all Fruits while innerResult will contain only these having Color

EDIT: specific solution applied inside mapping

Well, the default left join cannot be changed: Inner or Right Outer Join in Nhibernate and Fluent Nhibernate on Many to Many collection. But what about using other NHibernate feature:

Let's say that our Fruit, is only meaningful, if there is a Color. If this is true, and we won't ever need these table records without Color selected (having column ColorId set to NULL) there is a way how to adjust mapping:

// Mapping Fruit
Table("Fruits");
Where("colorId IS NOT NULL");
...

or in XML

  <class name="Fruit" table="Fruits" where="colorId IS NOT NULL" ... >

(see http://nhibernate.info/doc/nh/en/index.html#mapping-declaration-class)

So this, won't change LEFT to INNER, but at least the mapping will allow to have only colorful fruits...

Community
  • 1
  • 1
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
  • While this can be a valuable solution, I am looking for similar things in mapping, but not at query level. Thanks for your answer. – Wei Ma Nov 27 '12 at 23:38
  • I see. But I am afraid that this is only solution. Please take a look here: http://stackoverflow.com/questions/3057310. BUT! There is an option ... i extended my answer. – Radim Köhler Nov 28 '12 at 05:11
  • Thanks. I think that answers my question. – Wei Ma Nov 28 '12 at 18:37