Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between criteria and detached criteria in hibernate?

Tags:

hibernate

What is the difference between criteria and detached criteria? When should we go for criteria and when should we go for detached criteria?

like image 286
user964904 Avatar asked Oct 17 '11 13:10

user964904


People also ask

What is meant by criteria in Hibernate?

Criteria in Hibernate can be used for join queries by joining multiple tables, useful methods for Hibernate criteria join are createAlias(), setFetchMode() and setProjection() Criteria in Hibernate API can be used for fetching results with conditions, useful methods are add() where we can add Restrictions.

What is the purpose of the criteria interface in Hibernate?

The Hibernate Criteria Query Language (HCQL) is used to fetch the records based on the specific criteria. The Criteria interface provides methods to apply criteria such as retreiving all the records of table whose salary is greater than 50000 etc.

What is the benefit of Hibernate Criteria API?

In Hibernate, the Criteria API helps us build criteria query objects dynamically. Criteria is a another technique of data retrieval apart from HQL and native SQL queries. The primary advantage of the Criteria API is that it is intuitively designed to manipulate data without using any hard-coded SQL statements.

What is criteria builder in Hibernate?

Hibernate provides alternate ways of manipulating objects and in turn data available in RDBMS tables. One of the methods is Criteria API, which allows you to build up a criteria query object programmatically where you can apply filtration rules and logical conditions.


2 Answers

The detached criteria allows you to create the query without Session. Then you can execute the search in an arbitrary session.

In fact you should think carefully when using a detached criteria using another, or a new, session (no cache, and creation of the session).

They are most useful for join conditions, subselects, and to query outside the current session.

Another common use is for code reuse. Many developers declare them as static queries and execute them using the underlying session from different DAO.

like image 93
ssedano Avatar answered Oct 05 '22 16:10

ssedano


Using a DetachedCriteria is exactly the same as a Criteria except you can do the initial creation and setup of your query without having access to the session. When it comes time to run your query, you must convert it to an executable query with getExecutableCriteria(session).

This is useful if you are building complicated queries, possibly through a multi-step process, because you don't need access to the Session everywhere. You only need the Session at the final step when you run the query.

Under the hood, DetachedCriteria uses a CriteriaImpl which is the same class you get if you call session.createCriteria().

like image 34
takteek Avatar answered Oct 05 '22 18:10

takteek