views:

982

answers:

2

If I want to search those students who take class "Math" and "John" is his group:

shoud I use createCriteria or createAlias?

Criteria:

Criteria criteria = session.createCriteria(Student.class);
Criteria subquery1 = criteria.createCriteria("courses", course).add(Restrictions.eq(course.name, "Math"));
Criteria subquery2 = criteria.createCriteria("group", student).add(Restrictions.eq(student.name, "John"));

how to put subquery1 and subquery2 together with initial criteria?

Alias:

Criteria criteria = session.createCriteria(Student.class).
createAlias("courses", course).add(Restrictions.eq(course.name, "Math")).
createCriteria("group", student).add(Restrictions.eq(student.name, "John"));

When to use createCriteria and when createAlias? I think the boath are the same...

+2  A: 

CreateAlias and CreateCriteria are identical in the current versions of Hibernate and NHibernate. The only difference being that CreateCriteria has 2 additional overloads without the alias parameter.

Presumably they were different in a older version, but any differences are long gone.

An alias can be defined in terms of another alias, so your first example can be written as:

// Java
Criteria criteria = session.createCriteria(Student.class)
    .createAlias("courses", "course")
    .createAlias("course.group", "student")
    .add(Restrictions.eq("course.name", "Math"))
    .add(Restrictions.eq("student.name", "John"));

// C#
ICriteria criteria = session.CreateCriteria<Student>()
    .CreateAlias("Courses", "course")
    .CreateAlias("course.Group", "student")
    .Add(Restrictions.Eq("course.Name", "Math"))
    .Add(Restrictions.Eq("student.Name", "John"));
Lachlan Roche
sorry didn't tell you that i am using nhibernate for C#. So if i undesrtand correctly createAlias is the same as createCriteria, but createCriteria can use different join but createAlias can only use inner join. Am i right?
senzacionale
@senzacionale JoinType parameter is available via both method names.
Lachlan Roche
they are not the same thingnote that CreateCriteria exposes an ICriteria object which can be manipulated besides the "root" ICriteria objectcheck my answer athttp://stackoverflow.com/questions/899079/nhibernate-createcriteria-vs-createalias/921042#921042
Jaguar
A: 

Can i use also like this:

ICriteria criteria = session.CreateCriteria<Student>()
    .CreateCriteria("Courses", "course")
    .CreateCriteria("course.Group", "student")
    .Add(Restrictions.Eq("course.Name", "Math"))
    .Add(Restrictions.Eq("student.Name", "John"));

When use alias instead of criteria?

senzacionale
ok, sorry for mistake. Next time will use comment. So when then use alias and when criteria? Only when you need left or right join or somewhere else to?
senzacionale