A blog dedicated to demystifying technology through powerful knowledge sharing.
Explore bite-sized insights, real-world examples, and key takeaways on essential tech concepts — made simple, practical, and impactful for curious minds and seasoned professionals alike.
Mates, here is thefirst program in hibernatelike saving an object into the database (don’t think we are inserting a record into the databasethat is the case inJDBC, in hibernate we are justsaving an objectinto database, means inserting only)hope you got mycontention, as of now am giving this as normal console based java application, actually it’s bittedioustoset the class pathevery time for all thejarfiles but you must know this too.
From the next example i will give all the applications in theEclipse
As i told you earlier, these are the files we require to shape an hibernate program..
Product.java (My POJO class)
Product.hbm.xml (Xml mapping file )
hibernate.cfg.xml (Xml configuration file)
ClientForSave.java (java file to write our hibernate logic)
Product.java:
private int productId;
private String proName;
private double price;
public void setProductId(int productId)
{
this.productId = productId;
}
public int getProductId()
{
return productId;
}
public void setProName(String proName)
{
this.proName = proName;
}
public String getProName()
{
return proName;
}
public void setPrice(double price)
{
this.price = price;
}
public double getPrice()
{
return price;
}
Product.hbm.xml:
In this mapping file, my Product class is linked withPRODUCTStable in the database, and next is the id element, means in the database table what column we need to take asprimarykey column, that property name we need to give here, actually i have been given mypropertyname productId which will mapped with pid column in the table.
And proName is mapped with pname column of thePRODUCTStable, see i have not specified anycolumnfor the property price, this means that, our property name in the pojo class and the column name in the tablebothare same.
Remember: the first 3 lines is the DTD for the mapping file, as a programmer no need to remember but we need to be very careful while you are copying this DTD, program may not be executed if you write DTD wrong, actually we have separate DTD’s for Mapping xml and Configuration xml files.
hibernate.cfg.xml:
In this configuration file i have been given my Oracle database connection properties, if you are using MySql then just specify your database related details actually its depends on you.
Now compile all .java files and run ClientForSave.java and check the output
Output Eclipse
In The Database
Note:
Make sure all .class, .java, .xmlfiles are exist in the same folder
Before you compile and run this application, ensure you set theclass pathfor all12 jarsfiles, this is tedious like what i told you earlier, we can avoid this process from the next example with Eclipse, a real time tool
except select operation, all other operations must be in the Transaction Scope
Hibernate provides three different ways to retrieve data from database. TheCriteria Query APIlets you build nested, structured query expressions in Java, providing a compile-time syntax checking that is not possible with a query language like HQL or SQL. The Criteria API also includesquery by example (QBE)functionality. This lets you supply example objects that contain the properties you would like to retrieve instead of having to step-by-step spell out the components of the query. It also includes projection and aggregation methods, includingcount(). Let’s explore it’s different features in detail.y
Basic Usage Example
The Criteria API allows you to build up a criteria query object programmatically; theorg.hibernate.Criteriainterface defines the available methods for one of these objects. The HibernateSessioninterface contains severalcreateCriteria()methods. Pass the persistent object’s class or its entity name to thecreateCriteria()method, and Hibernate will create aCriteriaobject that returns instances of the persistence object’s class when your application executes a criteria query.
The simplest example of a criteria query is one with no optional parameters or restrictions—the criteria query will simply return every object that corresponds to the class.
Moving on from this simple example, we will add constraints to our criteria queries so we can whittle down the result set.
Using Restrictions with Criteria
The Criteria API makes it easy to use restrictions in your queries to selectively retrieve objects; for instance, your application could retrieve only products with a price over $30. You may add these restrictions to aCriteriaobject with theadd()method. Theadd()method takes anorg.hibernate.criterion.Criterionobject that represents an individual restriction. You can have more than one restriction for a criteria query.
i) Restrictions.eq() Example
To retrieve objects that have a property value that “equals” your restriction, use theeq()method onRestrictions, as follows:
Above query will search all products having description anything but not “Mouse”.
You cannot use the not-equal restriction to retrieve records with a NULL value in the database for that property (in SQL, and therefore in Hibernate, NULL represents the absence of data, and so cannot be compared with data). If you need to retrieve objects with NULL properties, you will have to use theisNull()restriction.
iii) Restrictions.like() and Restrictions.ilike() Example
Instead of searching for exact matches, we can retrieve all objects that have a property matching part of a given pattern. To do this, we need to create an SQL LIKE clause, with either thelike()or theilike()method. Theilike()method is case-insensitive.
Above example uses anorg.hibernate.criterion.MatchModeobject to specify how to match the specified value to the stored data. TheMatchModeobject (a type-safe enumeration) has four different matches:
ANYWHERE: Anyplace in the string
END: The end of the string
EXACT: An exact match
START: The beginning of the string
iv) Restrictions.isNull() and Restrictions.isNotNull() Example
TheisNull()andisNotNull()restrictions allow you to do a search for objects that have (or do not have) null property values.
v) Restrictions.gt(), Restrictions.ge(), Restrictions.lt() and Restrictions.le() Examples
Several of the restrictions are useful for doing math comparisons. The greater-than comparison isgt(), the greater-than-or-equal-to comparison isge(), the less-than comparison islt(), and the less-than-or-equal-to comparison isle(). We can do a quick retrieval of all products with prices over $25 like this, relying on Java’s type promotions to handle the conversion toDouble:
Moving on, we can start to do more complicated queries with the Criteria API. For example, we can combine AND and OR restrictions in logical expressions. When we add more than one constraint to a criteria query, it is interpreted as an AND, like so:
If we want to have two restrictions that return objects that satisfy either or both of the restrictions, we need to use theor()method on the Restrictions class, as follows:
The orExp logical expression that we have created here will be treated like any other criterion. We can therefore add another restriction to the criteria:
If we wanted to create an OR expression with more than two different criteria (for example, “price > 25.0 OR name like Mou% OR description not like blocks%”), we would use anorg.hibernate.criterion.Disjunctionobject to represent a disjunction.
You can obtain this object from thedisjunction()factory method on theRestrictionsclass. The disjunction is more convenient than building a tree of OR expressions in code. To represent an AND expression with more than two criteria, you can use theconjunction()method, although you can easily just add those to theCriteriaobject. The conjunction can be more convenient than building a tree of AND expressions in code. Here is an example that uses the disjunction:
sqlRestriction()restriction allows you to directly specify SQL in the Criteria API. It’s useful if you need to use SQL clauses that Hibernate does not support through the Criteria API.
Your application’s code does not need to know the name of the table your class uses. Use {alias} to signify the class’s table, as follows:
crit.add(Restrictions.sqlRestriction("{alias}.description like 'Mou%'"));
List results = crit.list();
Paging Through the ResultSet
One common application pattern that criteria can address is pagination through the result set of a database query. There are two methods on theCriteriainterface for paging, just as there are for Query:setFirstResult()andsetMaxResults(). ThesetFirstResult()method takes an integer that represents the first row in your result set, starting with row 0. You can tell Hibernate to retrieve a fixed number of objects with thesetMaxResults()method. Using both of these together, we can construct a paging component in our web or Swing application.
As you can see, this makes paging through the result set easy. You can increase the first result you return (for example, from 1, to 21, to 41, etc.) to page through the result set.
Obtaining a Unique Result
Sometimes you know you are going to return only zero or one object from a given query. This could be because you are calculating an aggregate or because your restrictions naturally lead to a unique result. If you want obtain a single Object reference instead of a List, theuniqueResult()method on theCriteriaobject returns an object or null. If there is more than one result, theuniqueResult()method throws aHibernateException.
The following short example demonstrates having a result set that would have included more than one result, except that it was limited with thesetMaxResults()method:
Again, please note that you need to make sure that your query returns only one or zero results if you use theuniqueResult()method. Otherwise, Hibernate will throw aNonUniqueResultExceptionexception.
Obtaining Distinct Results
If you would like to work with distinct results from a criteria query, Hibernate provides a result transformer for distinct entities,org.hibernate.transform.DistinctRootEntityResultTransformer, which ensures that no duplicates will be in your query’s result set.Rather than using SELECT DISTINCT with SQL, the distinct result transformer compares each of your results using their defaulthashCode()methods, and only adds those results with unique hash codes to your result set. This may or may not be the result you would expect from an otherwise equivalent SQL DISTINCT query, sobe careful with this.
An additional performance note: the comparison is done in Hibernate’s Java code, not at the database, so non-unique results will still be transported across the network.
Sorting the Query’s Results
Sorting the query’s results works much the same way with criteria as it would with HQL or SQL. The Criteria API provides theorg.hibernate.criterion.Orderclass to sort your result set in either ascending or descending order, according to one of your object’s properties.
This example demonstrates how you would use the Order class:
You may add more than oneOrderobject to theCriteriaobject. Hibernate will pass them through to the underlying SQL query. Your results will be sorted by the first order, then any identical matches within the first sort will be sorted by the second order, and so on. Beneath the covers,Hibernate passes this on to an SQL ORDER BY clause after substituting the proper database column name for the property.
Performing Associations (Joins)
The association works when going fromeither one-to-many or from many-to-one. First, we will demonstrate how to use one-to-many associations to obtain suppliers who sell products with a price over $25. Notice that we create a new Criteria object for the products property, add restrictions to the products’ criteria we just created, and then obtain the results from the supplier Criteria object:
suppCrit.add(Restrictions.eq("name","Hardware Are We"));
List results = crit.list();
Adding Projections and Aggregates
Instead of working with objects from the result set, you can treat the results from the result set as a set of rows and columns, also known as a projection of the data. This is similar to how you would use data from a SELECT query with JDBC.
To use projections, start by getting theorg.hibernate.criterion.Projectionobject you need from theorg.hibernate.criterion.Projectionsfactory class. TheProjectionsclass is similar to theRestrictionsclass in that it provides several static factory methods for obtainingProjectioninstances. After you get aProjectionobject, add it to your Criteria object with thesetProjection()method. When theCriteriaobject executes, the list contains object references that you can cast to the appropriate type.
Example 1 : Single Aggregate ( Getting Row Count )
Other aggregate functions available through theProjectionsfactory class include the following:
avg(String propertyName): Gives the average of a property’s value
count(String propertyName): Counts the number of times a property occurs
countDistinct(String propertyName): Counts the number of unique values the property contains
max(String propertyName): Calculates the maximum value of the property values
min(String propertyName): Calculates the minimum value of the property values
sum(String propertyName): Calculates the sum total of the property values
Example 2 : Multiple Aggregates
We can apply more than one projection to a given Criteria object. To add multiple projections, get a projection list from theprojectionList()method on the Projections class. Theorg.hibernate.criterion.ProjectionListobject has anadd()method that takes aProjectionobject. You can pass the projections list to thesetProjection()method on theCriteriaobject becauseProjectionListimplements theProjectioninterface.
Another use of projections is to retrieve individual properties, rather than entities. For instance, we can retrieve just the name and description from our product table, instead of loading the entire object representation into memory.
In QBE, instead of programmatically building aCriteriaobject withCriterionobjects and logical expressions, you can partially populate an instance of the object. You use this instance as a template and have Hibernate build the criteria for you based upon its values. This keeps your code clean and makes your project easier to test.
For instance, if we have a user database, we can construct an instance of a user object, set the property values for type and creation date, and then use theCriteriaAPI to run a QBE query. Hibernate will return a result set containing all user objects that match the property values that were set. Behind the scenes, Hibernate inspects the Example object and constructs an SQL fragment that corresponds to the properties on the Example object.
The following basic example searches for suppliers that match the name on the example Supplier object:
Using the Criteria API is an excellent way to get started developing with HQL. The developers of Hibernate have provided a clean API for adding restrictions to queries with Java objects. Although HQL isn’t too difficult to learn, some developers prefer the Criteria Query API, as it offers compile-time syntax checking—although column names and other schema-dependent information cannot be checked until run time.