Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
725 views
in Technique[技术] by (71.8m points)

nhibernate - hibernate - createCriteria or createAlias?

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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...