Best Hibernate Training In Adyar Chennai With Placement

Hibernate Training

Hibernate Training In Chennai and Kodo are two popular ORM solutions for Java applications. This tutorial provides step by step instructions for Hibernate applications but for minor differences, could also be used with Kodo. Hibernate provides data query and retrieval facilities that significantly reduce development time. Hibernate lets you develop persistent classes following object-oriented idiom — including association, inheritance, polymorphism, composition, and collections. Hibernate allows you to express queries in its own portable SQL extension (HQL), as well as in native SQL, or with an object-oriented Criteria and Example API.

Workshop

Workshop offers unparalleled support for the development of sophisticated web applications based on industry standards like JSF, EJB3, and JSP and popular frameworks like Spring, Hibernate, Struts and Tiles. Workshop includes sophisticated WYSIWYG editors and Oracle’s AppXRay technology, which provides a deep level of understanding of the web application as a whole, thereby providing unprecedented depth and capabilities in code completion, consistency checking with generated classes, configuration files or annotations, pre-build error checking, and validation that reaches all the levels of your application.

Workshop includes database management and O/R mapping tools, including updated Hibernate support.

  • DbXplorer™ — Database explorer for all popular databases including Oracle, DB2, Sybase, SQL Server and MySQL
  • DbXaminer™ — View Database Diagrams and SQL Editor
  • Hibernate EJB3 Entity Manager, Hibernate Entities Editor
  • HQL Editor, Hibernate Mapping Editor
  • Add Hibernate support to existing projects
  • AppXRay™ power for all the above — providing code completion, error checking and validation that extends to Hibernate related files and classes

Hibernate Query Language

Hibernate Query Language (HQL) is an object-oriented query language, similar to SQL, but instead of operating on tables and columns, HQL works with persistent objects and their properties. HQL queries are translated by Hibernate into conventional SQL queries which in turns perform action on database.

Although you can use SQL statements directly with Hibernate using Native SQL but I would recommend to use HQL whenever possible to avoid database portability hassles, and to take advantage of Hibernate’s SQL generation and caching strategies.

Keywords like SELECT , FROM and WHERE etc. are not case sensitive but properties like table and column names are case sensitive in HQL.

FROM Clause

You will use FROM clause if you want to load a complete persistent objects into memory. Following is the simple syntax of using FROM clause:

String hql = "FROM Employee";
Query query = session.createQuery(hql);
List results = query.list();

If you need to fully qualify a class name in HQL, just specify the package and class name as follows:

String hql = "FROM com.hibernatebook.criteria.Employee";
Query query = session.createQuery(hql);
List results = query.list();

AS Clause

The AS clause can be used to assign aliases to the classes in your HQL queries, specially when you have long queries. For instance, our previous simple example would be the following:

String hql = "FROM Employee AS E";
Query query = session.createQuery(hql);
List results = query.list();

The AS keyword is optional and you can also specify the alias directly after the class name, as follows:

String hql = "FROM Employee E";
Query query = session.createQuery(hql);
List results = query.list();

SELECT Clause

The SELECT clause provides more control over the result set than the from clause. If you want to obtain few properties of objects instead of the complete object, use the SELECT clause. Following is the simple syntax of using SELECT clause to get just first_name field of the Employee object:

String hql = "SELECT E.firstName FROM Employee E";
Query query = session.createQuery(hql);
List results = query.list();

It is notable here that Employee.firstName is a property of Employee object rather than a field of the EMPLOYEE table.

WHERE Clause

If you want to narrow the specific objects that are returned from storage, you use the WHERE clause. Following is the simple syntax of using WHERE clause:

String hql = "FROM Employee E WHERE E.id = 10";
Query query = session.createQuery(hql);
List results = query.list();

ORDER BY Clause

To sort your HQL query’s results, you will need to use the ORDER BY clause. You can order the results by any property on the objects in the result set either ascending (ASC) or descending (DESC). Following is the simple syntax of using ORDER BY clause:

String hql = "FROM Employee E WHERE E.id > 10 ORDER BY E.salary DESC";
Query query = session.createQuery(hql);
List results = query.list();

If you wanted to sort by more than one property, you would just add the additional properties to the end of the order by clause, separated by commas as follows:

String hql = "FROM Employee E WHERE E.id > 10 " +
"ORDER BY E.firstName DESC, E.salary DESC ";
Query query = session.createQuery(hql);
List results = query.list();

GROUP BY Clause

This clause lets Hibernate pull information from the database and group it based on a value of an attribute and, typically, use the result to include an aggregate value. Following is the simple syntax of using GROUP BY clause:

String hql = "SELECT SUM(E.salary), E.firtName FROM Employee E " +
"GROUP BY E.firstName";
Query query = session.createQuery(hql);
List results = query.list();

Using Named Paramters

Hibernate supports named parameters in its HQL queries. This makes writing HQL queries that accept input from the user easy and you do not have to defend against SQL injection attacks. Following is the simple syntax of using named parameters:

String hql = "FROM Employee E WHERE E.id = :employee_id";
Query query = session.createQuery(hql);
query.setParameter("employee_id",10);
List results = query.list();

UPDATE Clause

Bulk updates are new to HQL with Hibernate 3, and deletes work differently in Hibernate 3 than they did in Hibernate 2. The Query interface now contains a method called executeUpdate() for executing HQL UPDATE or DELETE statements.

The UPDATE clause can be used to update one or more properties of an one or more objects. Following is the simple syntax of using UPDATE clause:

String hql = "UPDATE Employee set salary = :salary "  + 
"WHERE id = :employee_id";
Query query = session.createQuery(hql);
query.setParameter("salary", 1000);
query.setParameter("employee_id", 10);
int result = query.executeUpdate();
System.out.println("Rows affected: " + result);

DELETE Clause

The DELETE clause can be used to delete one or more objects. Following is the simple syntax of using DELETE clause:

String hql = "DELETE FROM Employee "  + 
"WHERE id = :employee_id";
Query query = session.createQuery(hql);
query.setParameter("employee_id", 10);
int result = query.executeUpdate();
System.out.println("Rows affected: " + result);

INSERT Clause

HQL supports INSERT INTO clause only where records can be inserted from one object to another object. Following is the simple syntax of using INSERT INTO clause:

String hql = "INSERT INTO Employee(firstName, lastName, salary)"  + 
"SELECT firstName, lastName, salary FROM old_employee";
Query query = session.createQuery(hql);
int result = query.executeUpdate();
System.out.println("Rows affected: " + result);

Aggregate Methods

HQL supports a range of aggregate methods, similar to SQL. They work the same way in HQL as in SQL and following is the list of the available functions:

S.N.FunctionsDescription1avg(property name)The average of a property’s value2count(property name or *)The number of times a property occurs in the results3max(property name)The maximum value of the property values4min(property name)The minimum value of the property values5sum(property name)The sum total of the property values

The distinct keyword only counts the unique values in the row set. The following query will return only unique count:

String hql = "SELECT count(distinct E.firstName) FROM Employee E";
Query query = session.createQuery(hql);
List results = query.list();

Pagination using Query

There are two methods of the Query interface for pagination.

S.N.Method & Description1Query setFirstResult(int startPosition)

This method takes an integer that represents the first row in your result set, starting with row 0.

2Query setMaxResults(int maxResult)

This method tells Hibernate to retrieve a fixed number maxResults of objects.

Using above two methods together, we can construct a paging component in our web or Swing application. Following is the example which you can extend to fetch 10 rows at a time:

String hql = "FROM Employee";
Query query = session.createQuery(hql);
query.setFirstResult(1);
query.setMaxResults(10);
List results = query.list();

Web Application with Hibernate

Here, we are going to create a web application with hibernate. For creating the web application, we are using JSP for presentation logic, Bean class for representing data and DAO class for database codes.

As we create the simple application in hibernate, we don’t need to perform any extra operations in hibernate for creating web application. In such case, we are getting the value from the user using the JSP file.

Example to create web application using hibernate

In this example, we are going to insert the record of the user in the database. It is simply a registration form.


index.jsp

This page gets input from the user and sends it to the register.jsp file using post method.

  1. <form action=”register.jsp” method=”post”>
  2. Name:<input type=”text” name=”name”/><br><br/>
  3. Password:<input type=”password” name=”password”/><br><br/>
  4. Email ID:<input type=”text” name=”email”/><br><br/>
  5. <input type=”submit” value=”register”/>”
  6. </form>

register.jsp

This file gets all request parameters and stores this information into an object of User class. Further, it calls the register method of UserDao class passing the User class object.

  1. <%@page import=”com.javatpoint.mypack.UserDao”%>
  2. <jsp:useBean id=”obj” class=”com.javatpoint.mypack.User”>
  3. </jsp:useBean>
  4. <jsp:setProperty property=”*” name=”obj”/>
  5. <%
  6. int i=UserDao.register(obj);
  7. if(i>0)
  8. out.print(“You are successfully registered”);
  9. %>

User.java

It is the simple bean class representing the Persistent class in hibernate.

  1. package com.javatpoint.mypack;
  2. public class User {
  3. private int id;
  4. private String name,password,email;
  5. //getters and setters
  6. }

user.hbm.xml

It maps the User class with the table of the database.

  1. <?xml version=’1.0' encoding=’UTF-8'?>
  2. <!DOCTYPE hibernate-mapping PUBLIC
  3. “-//Hibernate/Hibernate Mapping DTD 3.0//EN”
  4. “http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
  5. <hibernate-mapping>
  6. <class name=”com.javatpoint.mypack.User” table=”u400">
  7. <id name=”id”>
  8. <generator class=”increment”></generator>
  9. </id>
  10. <property name=”name”></property>
  11. <property name=”password”></property>
  12. <property name=”email”></property>
  13. </class>
  14. </hibernate-mapping>

UserDao.java

A Dao class, containing method to store the instance of User class.

  1. package com.javatpoint.mypack;
  2. import org.hibernate.Session;
  3. import org.hibernate.Transaction;
  4. import org.hibernate.cfg.Configuration;
  5. public class UserDao {
  6. public static int register(User u){
  7. int i=0;
  8. Session session=new Configuration().
  9. configure().buildSessionFactory().openSession();
  10. Transaction t=session.beginTransaction();
  11. t.begin();
  12. i=(Integer)session.save(u);
  13. t.commit();
  14. session.close();
  15. return i;
  16. }
  17. }

hibernate.cfg.xml

It is a configuration file, containing informations about the database and mapping file.

  1. <?xml version=’1.0' encoding=’UTF-8'?>
  2. <!DOCTYPE hibernate-configuration PUBLIC
  3. “-//Hibernate/Hibernate Configuration DTD 3.0//EN”
  4. “http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
  5. <hibernate-configuration>
  6. <session-factory>
  7. <property name=”hbm2ddl.auto”>create</property>
  8. <property name=”dialect”>org.hibernate.dialect.Oracle9Dialect</property>
  9. <property name=”connection.url”>jdbc:oracle:thin:@localhost:1521:xe</property>
  10. <property name=”connection.username”>system</property>
  11. <property name=”connection.password”>oracle</property>
  12. <property name=”connection.driver_class”>oracle.jdbc.driver.OracleDriver</property>
  13. <mapping resource=”user.hbm.xml”/>
  14. </session-factory>
  15. </hibernate-configuration>