Difference between createCriteria and createAlias - java

I was reading hibernate criteria document here:
http://docs.jboss.org/hibernate/orm/3.6/javadocs/org/hibernate/Criteria.html
I had used it many time and I am normally use createAlias() to join table, here they have provide two methods to make a join and fetch data from the tables, there are:
List cats = session.createCriteria(Cat.class)
.createCriteria("kittens")
.add( Restrictions.like("name", "Iz%") )
.list();
List cats = session.createCriteria(Cat.class)
.createAlias("kittens", "kit")
.add( Restrictions.like("kit.name", "Iz%") )
.list();
So I am not able to distinguish difference between .createCriteria("kittens") and createAlias("kittens", "kit") or may be I am not getting what this code exactly do, can someone help me to clear my confusion.

The only difference is that CreateCriteria has 2 additional
overloads without the alias parameter, this difference is long gone in
the latest versions.
But essentially the application is slightly
different in its usage is that CreateCriteria uses its relations of
mapping from parent to child, whilst with CreateAlias you defined them
with your customized alias names from the root.
Read more from here.

Main Difference is that Criterias' createCriteria() creates and returns Sub Criteria (new Criteria Object).This is useful if you want to create criteria for subquery.
Here is what documentation says about its return type
Returns:
the created "sub criteria"
Criteria's CreateAlias() returns existing Criteria Object
Here is what documentation says about its return type
Returns:
this (for method chaining)

Related

Hibernate 4 finding record by property

Is there any specific method for finding record from database?
I don't want to use criteria api and load() only fetch data using primary key but what about if i want to find records using other columns? I know it is possible with criteria but want to know is there any other option?
From our discussion in chat. OP was looking for a way to query using combinations of entity fields only known at runtime. I've suggested Criteria - Example Queries.
Sample from official documentation:
Cat cat = new Cat();
cat.setSex('F');
cat.setColor(Color.BLACK);
List results = session.createCriteria(Cat.class)
.add( Example.create(cat) )
.list();
As far As I know there is no method directly for that ..
You can try using HQL or Native SQL query.
And
In criteria API you need to add Projections to fetch the required properties on POJO's

When use createQuery() and find() methods of EntityManager?

I would like to know the difference between on these methods.
When use the createQuery()and find() methods of EntityManager ?
What the advantages about each of them ?
Thank you for answer me.
You use find when you want to look up an entity by primary key. That means you know exactly what you're looking for, you just want to pull it out of the database.
You use createQuery when you want to find entities using criteria or if you want to use a JPQL statement to define what you get back. So you would use the query when you want to get an entity or collection of entities matching some conditions.
The createQuery method allows you to create a JPQL statement that will be executed. The JPQL statement allowed is much more dynamic than the one executed by find. For example given the following table:
create table CAT(
cat_id integer,
cat_name varchar(40)
)
You could execute a query to find the cat by name.
entityManager.createQuery("select c from Cat c where c.name = :name");
The find method only allows you to retreive an object using its primary key. So to use the find method for the above table:
entityManager.find(Cat.class, new Integer(1));
In a nutshell, createQuery allows you to retrieve entities in a more dynamic fashion, while find limits you to searching for an entity with a known id.

Hibernate and how to avoid name change of modals

I am using Hibernate for a few years but am not sure about the usage of Query and Criteria.
I understood, that one of Hibernate strengths are to control the field name in one place.
If I have the following code:
List cats = sess.createCriteria(Cat.class)
.add( Restrictions.like("name", "Fritz%") )
.add( Restrictions.between("weight", minWeight, maxWeight) )
.list();
What if I change "name" of the Cat in the java object?
Even when using refactor replace (like in Elipse) it will not detect the element as something that needs to be changed!
If so , how do you maintain the field names in Java?
I believe type safe queries are not supported in Hibernate specific api. JPA 2 however has support for it. Read this: Dynamic, typesafe queries in JPA 2.0
I've got the same problem in the past, and actually there's no way to have a typed and refactor resistant(change name) reference of a field in java, so is neither possible have a query builder that allow this, but i tried to build a implementation of a query builder that using some workaround try to allow you to write type safe and refactor resistant query, it's name is ObjectQuery and you can found some information about here.
let me know if it solve your use case !
obviously is nothing of standard so if you are looking to something of standard, is better JPA Typesafe but it not have the same power!

Question about Criteria.createCriteria in Hibernate API

So I'm still trying to get myself acquainted with the Hibernate Criteria API, and I have this piece of Java code which I would like to seek clarification over.
Criteria c = super.getSession().createCriteria(PpNnCtDetail.class);
c.add(Restrictions.between("commencementDate", fromDate, toDate);
This part I understand what's happening - putting it in terms of SQL it would be something like - correct me if I'm wrong,
SELECT * FROM PpNnCtDetail WHERE commencementDate >= fromDate AND commencementDate <= toDate;
The problem comes with the code following the two lines above.
c = c.createCriteria("nnContractTbl");
c.createCriteria("progCategory").add(Restrictions.in("progCategoryId", allProgCat));
c.createCriteria("acadOrgTbl");
c.createCriteria("serviceType");
c.createCriteria("campusTbl");
return c.list();
What is the first line trying to accomplish? Is that assignment back to c redundant?
In fact, what are the lines c.createCriteria trying to achieve? What would an equivalent SQL query look like? More importantly, what would c.list() return?
The assignament on c = c.createCriteria("nnContractTbl"); is redundant, createCriteria and almost all Criteria methods modify the instance they're invoked on, and return the instance itself for method chanining. So you can chain calls like this:
return super.getSession().createCriteria(PpNnCtDetail.class)
.add(Restrictions.between("commencementDate", fromDate, toDate)
.createCriteria("nnContractTbl")
.createCriteria("progCategory").add(Restrictions.in("progCategoryId", allProgCat))
.createCriteria("acadOrgTbl")
.createCriteria("serviceType")
.createCriteria("campusTbl")
.list();
And about the result of that sequence, Criteria.createCriteria(association) will result in an inner join between the data already in the criteria and the table designed in the association modelled by the attribute association. It will also "root" (as they state in the Javadocs) the Criteria at the association entity, so that in further calls to createCriteria(association), association refers to an association attribute declared on the last "rooted" entity.
It's a shorthand for Criteria.createCriteria(association, joinType) with joinType CriteriaSpecification.INNER_JOIN.
Those createCriteria as specified above are basically equivalent to an INNER JOIN to the entity passed.
The best way to find answers to your questions (and also learn hibernate in the meantime) is to turn SQL logging on in your hibernate configuration file, and inspect the generated SQL.

Does Hibernate's Criteria API still not support nested relations

I'd like to use Hibernate's Criteria API for precisely what everybody says is probably its most likely use case, applying complex search criteria. Problem is, the table that I want to query against is not composed entirely of primitive values, but partially from other objects, and I need to query against those object's id's.
I found this article from 2 years ago that suggests it's not possible. Here's how I tried it to no avail, there are other aspect of Hibernate where I know of where this sort of dot notation is supported within string literals to indicate object nesting.
if (!lookupBean.getCompanyInput().equals("")) {
criteria.add(Restrictions.like("company.company", lookupBean.getCompanyInput() + "%"));
}
EDIT:
Here's my correctly factored code for accomplishing what I was trying above, using the suggestion from the first answer below; note that I am even using an additional createCriteria call to order on an attribute in yet another associated object/table:
if (!lookupBean.getCompanyValue().equals("")) {
criteria.createCriteria("company").add(
Restrictions.like("company", lookupBean.getCompanyValue() + "%"));
}
List<TrailerDetail> tdList =
criteria.createCriteria("location").addOrder(Order.asc("location")).list();
Not entirely sure I follow your example, but it's certainly possible to specify filter conditions on an associated entity, simply by nesting Criteria objects to form a tree. For example, if I have an entity called Order with a many-to-one relationship to a User entity, I can find all orders for a user named Fred with a query like this:
List<Order> orders = session.createCriteria(Order.class)
.createCriteria("user")
.add(eq("name", "fred"))
.list();
If you're talking about an entity that has a relationship to itself, that should work as well. You can also replace "name" with "id" if you need to filter on the ID of an associated object.

Categories