hibernate - createCriteria or createAlias?

点点圈 提交于 2019-11-27 18:32:58

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

Adding to xavierzhoa's answer:

There is actually quite a big difference between the two methods which you will notice if you chain Criteria methods. You will continue to work on the original Criteria object when using createAlias, whereas you work on a more nested scope when using createCriteria.

Consider this:

    Criteria c = getSession()
      .createCriteria(YourEntity.class)
      .createCriteria("someMember", "s")
      .add(Restrictions.eq("name", someArgument));  // checks YourEntity.someMember.name

versus

    Criteria c = getSession()
      .createCriteria(YourEntity.class)
      .createAlias("someMember", "s")
      .add(Restrictions.eq("name", someArgument));  // checks  YourEntity.name

However, if you always assign and use an alias you will be able to work around the difference. Like:

    Criteria c = getSession()
      .createCriteria(YourEntity.class, "y")
      .createAlias("someMember", "s")
      .add(Restrictions.eq("y.name", someArgument));  // no more confusion

Please refer to the following source code from the Hibernate

public Criteria createCriteria(String associationPath, String alias, int joinType) {
    return new Subcriteria( this, associationPath, alias, joinType );
}


public Criteria createAlias(String associationPath, String alias, int joinType) {
    new Subcriteria( this, associationPath, alias, joinType );
    return this;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!