Hibernate usage of alias with criteria
Asked Answered
H

1

6

I am a bit confused about aliases to be honest so I am hoping someone can help me understand them better. In order to explain what I am missing I will use examples.

Lets say that I have:

Criteria criteria = session.createCriteria(Car.class)
criteria.createAlias("doors", "doors");

That means that now I can use some Restrcitions to find a door that is on left side of the Car or something along those lines.

Now my question is if I where to add multiple alias:

criteria.createAlias("doors", "doors").createAlias("doors.keytype", "keytype");

and

criteria.createAlias("tier".tier);

What does this mean? That my criteria object has all of those aliases? In which case what will getAlias() method return?

From the API:

Get the alias of the entity encapsulated by this criteria instance.

I was under the impression that all of the alias are encapsulated by this instance? Am I wrong? Did I somehow lost my first alias?

Also if I do something like:

Criteria criteri2 = criteria.createAlias("tier".tier);

Does this mean that both criteria and criteria2 point are the same Criteria or diff and which one points to what alias?

Furthermore given that each createAlias returns a Criteria should I assign that to the original criteria or to the new one?

Well I hope you can see my confusion.

Herbarium answered 25/2, 2013 at 23:7 Comment(0)
D
4

What does this mean? That my criteria object has all of those aliases?

Yes

In which case what will getAlias() method return?

The getAlias returns the alias of the class used in the createCriteria(Car.class) - you haven't used one but you could specify: createCriteria(Car.class, "c"), in which criteria.getAlias() would return c.

Does this mean that both criteria and criteria2 point are the same Criteria or diff and which one points to what alias?

Most methods in Criteria API return the own criteria in order to support chaining, for facility of use. You don't need to save the returned criteria instance since the object (and its internal properties) is being internally altered.

criteria.createAlias("a.b", "a_b").add(Restrictions.eq("a_b", value));

is similar to

criteria.createAlias("a.b", "a_b");
criteria.add(Restrictions.eq("a_b", value));

so ...

Furthermore given that each createAlias returns a Criteria should I assign that to the original criteria or to the new one?

... No. It wouldn't be viable for the guys at hibernate to limit the Criteria specification to obligate the programmer to save the returned instance, and it would kinda go against the OO standards to assume that the criteria object is not altered.

Denisse answered 21/11, 2014 at 9:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.