Hibernate is the ORM tool. HQL(Hibernate Query Language) is one of feature of Hibernate. Now i am explaining how to prepare HQL queries in Hibernate .HQL is an Object oriented language. HQL can communicate with DB from java code. Generally DB queries related to corresponding Databases that means DB queries are Database dependent. But HQL queries are database independent because of java pojo based programming language. Main advantage of HQL is even we change the database(Oracle to SQL Server) no need to change the java code to change database specific queries in java side. Because HQL queries are Pojo based not Database specific. In hibernate mapping file we are mapping java code with table structure. In the below example we are mapping java class with database table.
Java code:
public class Employee {
private int id;
private String firstName;
private int salary;
public Employee() {}
public Employee(String fname, int salary) {
this.firstName = fname;
this.salary = salary;
}
public int getId() {
return id;
}
public void setId( int id ) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName( String last_name ) {
this.lastName = last_name;
}
public int getSalary() {
return salary;
}
public void setSalary( int salary ) {
this.salary = salary;
}
}
This is table structure for above mentioned java code.
Table structure:
create table EMPLOYEE (
id INT NOT NULL auto_increment,
first_name VARCHAR(20) default NULL,
salary INT default NULL,
PRIMARY KEY (id)
);
This is configuration file to map java code with database table
Hibernate Mapping:
<hibernate-mapping>
<class name="Employee" table="EMPLOYEE">
<id name="id" type="int" column="id">
<generator class="sequence"/> **here sequence is the algorithm to generate unique id for each row in the table.
</id>
<property name="firstName" column="first_name" type="string"/>
<property name="salary" column="salary" type="int"/>
</class>
</hibernate-mapping>
Hql queries are looks like SQL queries
Example Hql Queries:
1.String hql = "FROM Employee AS E";
2.String hql = "FROM Employee E WHERE E.id = 10";
3.String hql = "FROM Employee E WHERE E.id > 10 ORDER BY E.salary DESC";
4.String hql = "SELECT SUM(E.salary), E.firtName FROM Employee E " + "GROUP BY E.firstName";
In the above HQL queries Employee is the java class and elements(id, salary, firstName) are properties of the class. when we fire the query from java code, based on hibernate mapping file hql will convert into corresponding database query.
Thursday, 17 July 2014
HQL Introduction
Subscribe to:
Post Comments (Atom)
great
ReplyDelete