0% found this document useful (0 votes)
5 views46 pages

Module 4

Module 4 covers the Hibernate Framework, an open-source ORM tool that simplifies database interactions in Java applications. It outlines Hibernate's architecture, lifecycle states of entities, advantages, and integration with Spring MVC, including configuration and example code for creating a user entity and repository. The document also emphasizes the importance of persistent classes and provides guidelines for implementing Hibernate in a Java application.

Uploaded by

madanmadhu818
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views46 pages

Module 4

Module 4 covers the Hibernate Framework, an open-source ORM tool that simplifies database interactions in Java applications. It outlines Hibernate's architecture, lifecycle states of entities, advantages, and integration with Spring MVC, including configuration and example code for creating a user entity and repository. The document also emphasizes the importance of persistent classes and provides guidelines for implementing Hibernate in a Java application.

Uploaded by

madanmadhu818
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

MODULE 4

HIBERNATE FRAMEWORK

STRUCTURE:

[Link] Objectives

[Link] Framework

[Link] Implementation :

[Link] Query Language :

[Link] :

[Link] SQL :

Hibernate is a Java framework that simplifies the development of Java application to interact
with the database. It is an open source, lightweight, ORM (Object Relational Mapping) tool.
Hibernate implements the specifications of JPA (Java Persistence API) for data persistence.

ORM Tool

An ORM tool simplifies the data creation, data manipulation and data access. It is a
programming technique that maps the object to the data stored in the database.

The ORM tool internally uses the JDBC API to interact with the database.

What is JPA?

Java Persistence API (JPA) is a Java specification that provides certain functionality and
standard to ORM tools. The [Link] package contains the JPA classes and
interfaces.

38
Advantages of Hibernate Framework

Following are the advantages of hibernate framework:

1) Open Source and Lightweight

Hibernate framework is open source under the LGPL license and lightweight.

2) Fast Performance

The performance of hibernate framework is fast because cache is internally used in hibernate
framework. There are two types of cache in hibernate framework first level cache and second
level cache. First level cache is enabled by default.

Database Independent Query

HQL (Hibernate Query Language) is the object-oriented version of SQL. It generates the
database independent queries. So you don't need to write database specific queries. Before
Hibernate, if database is changed for the project, we need to change the SQL query as well that
leads to the maintenance problem.

4) Automatic Table Creation

Hibernate framework provides the facility to create the tables of the database automatically. So
there is no need to create tables in the database manually.

5) Simplifies Complex Join

Fetching data from multiple tables is easy in hibernate framework.

6) Provides Query Statistics and Database Status

Hibernate supports Query cache and provide statistics about query and database status.

The Hibernate architecture is categorized in four layers.

o Java application layer

o Hibernate framework layer

o Backhand api layer

o Database layer

39
Let's see the diagram of hibernate architecture:

40
This is the high level architecture of Hibernate with mapping file and configuration file

Hibernate framework uses many objects such as session factory, session, transaction etc. along
with existing Java API such as JDBC (Java Database Connectivity), JTA (Java Transaction
API) and JNDI (Java Naming Directory Interface).

Elements of Hibernate Architecture

For creating the first hibernate application, we must know the elements of Hibernate architecture.

They are as follows:

41
Session Factory

The Session Factory is a factory of session and client of Connection Provider. It holds second
level cache (optional) of data. The [Link] Factory interface provides factory
method to get the object of Session.

Session

The session object provides an interface between the application and data stored in the
database. It is a short-lived object and wraps the JDBC connection. It is factory of Transaction,
Query and Criteria. It holds a first-level cache (mandatory) of data. The [Link]
interface provides methods to insert, update and delete the object. It also provides factory
methods for Transaction, Query and Criteria.

Transaction

The transaction object specifies the atomic unit of work. It is optional. The
[Link] interface provides methods for transaction management.

Connection Provider

It is a factory of JDBC connections. It abstracts the application from Driver Manager or Data
Source. It is optional.

Transaction Factory

It is a factory of Transaction. It is optional.

Life Cycle of Hibernate:

There are mainly four states of the Hibernate Lifecycle :

1. Transient State

2. Persistent State

3. Detached State

4. Removed State

42
State 1: Transient State

The transient state is the first state of an entity object. When we instantiate an object of
a POJO class using the new operator then the object is in the transient state. This object is
not connected with any hibernate session. As it is not connected to any Hibernate Session,
So this state is not connected to any database table. So, if we make any changes in the data
of the POJO Class then the database table is not altered. Transient objects are independent of
Hibernate, and they exist in the heap memory.

There are two layouts in which transient state will occur as follows:

1. When objects are generated by an application but are not connected to any
session.

2. The objects are generated by a closed session.

Here, we are creating a new object for the Employee class. Below is the code which shows
the initialization of the Employee object :

Employee e = new Employee();

[Link](21);

[Link]("Neha");

[Link]("Shri");

43
[Link]("Rudra");

State 2: Persistent State

Once the object is connected with the Hibernate Session then the object moves into the
Persistent State. So, there are two ways to convert the Transient State to the Persistent State
:

1. Using the hibernated session, save the entity object into the database table.

2. Using the hibernated session, load the entity object into the database table.

In this state. each object represents one row in the database table. Therefore, if we make
any changes in the data then hibernate will detect these changes and make changes in the
database table.

Following are the methods given for the persistent state:

• [Link](e);

• [Link](e);

• [Link](e);

• [Link](e);

• [Link](e);

• [Link](e);

Example:

Employee e = new Employee("Neha Shri Rudra", 21, 180103);

44
//Persistent State

[Link](e);

For converting an object from Persistent State to Detached State, we either have to close the
session or we have to clear its cache. As the session is closed here or the cache is cleared,
then any changes made to the data will not affect the database table. Whenever needed, the
detached object can be reconnected to a new hibernate session. To reconnect the detached
object to a new hibernate session, we will use the following methods as follows:

• merge()

• update()

• load()

• refresh()

Following are the methods used for the detached state :

• [Link](e);

• [Link](e);

• [Link]();

• [Link]();

Example

// Transient State

Employee e = new Employee("Neha Shri Rudra", 21, 180103);

// Persistent State

[Link](e);

45
// Detached State

[Link]();

State 4: Removed State

In the hibernate lifecycle it is the last state. In the removed state, when the entity object is
deleted from the database then the entity object is known to be in the removed state. It is
done by calling the delete() operation. As the entity object is in the removed state, if any
change will be done in the data will not affect the database table.

To make a removed entity object we will call [Link]().

Example

// Java Pseudo code to Illustrate Remove State

// Transient State

Employee e = new Employee();

Session s = [Link]();

[Link](01);

// Persistent State

[Link](e)

// Removed State

[Link](e);

46
persistent Classes :

The entire concept of Hibernate is to take the values from Java class attributes and persist them
to a database table. A mapping document helps Hibernate in determining how to pull the values
from the classes and map them with table and associated fields.

Java classes whose objects or instances will be stored in database tables are called persistent
classes in Hibernate. Hibernate works best if these classes follow some simple rules, also
known as the Plain Old Java Object (POJO) programming model.

There are following main rules of persistent classes, however, none of these rules are hard
requirements −

• All Java classes that will be persisted need a default constructor.

• All classes should contain an ID in order to allow easy identification of your objects
within Hibernate and the database. This property maps to the primary key column of a
database table.

• All attributes that will be persisted should be declared private and


have getXXX and setXXX methods defined in the JavaBean style.

• A central feature of Hibernate, proxies, depends upon the persistent class being either
non-final, or the implementation of an interface that declares all public methods.

• All classes that do not extend or implement some specialized classes and interfaces
required by the EJB framework.

The POJO name is used to emphasize that a given object is an ordinary Java Object, not a
special object, and in particular not an Enterprise JavaBean.

Simple POJO Example

Based on the few rules mentioned above, we can define a POJO class as follows −

public class Employee {

private int id;

private String firstName;

private String lastName;

private int salary;

47
public Employee() {}

public Employee(String fname, String lname, int salary) {

[Link] = fname;

[Link] = lname;

[Link] = salary;

public int getId() {

return id;

public void setId( int id ) {

[Link] = id;

public String getFirstName() {

return firstName;

public void setFirstName( String first_name ) {

[Link] = first_name;

public String getLastName() {

return lastName;

48
public void setLastName( String last_name ) {

[Link] = last_name;

public int getSalary() {

return salary;

public void setSalary( int salary ) {

[Link] = salary;

[Link] Implementation :

Spring MVC is a popular model view controller framework that handles dependency
injection at run time. Hibernate 5 is an ORM framework that acts as an abstraction over the
database. It allows interaction with the underlying database by removing any implementation
details which is handled by hibernate. In this article, we will integrate Spring MVC and
Hibernate 5 with an in-memory database h2.

Requirements

• Maven

• IDE (Preferably IntelliJ)

• Java 8+

49
Required Dependencies

After creating an empty project you will need some core dependencies which are required
for a bootstrap setup. In the dependencies section of your [Link] add the following
dependencies

spring-orm

The spring-orm module provides integration with hibernate

<dependency>

<groupId>[Link]</groupId>

<artifactId>spring-orm</artifactId>

<version>[Link]</version>

</dependency>

hibernate-core

Core hibernate module for the hibernate dependencies

• XML

• <dependency>
• <groupId>[Link]</groupId>
• <artifactId>hibernate-core</artifactId>
• <version>[Link]</version>
• </dependency>

h2-database

In-memory database

• XML

50
<dependency>

<groupId>com.h2database</groupId>

<artifactId>h2</artifactId>

<version>1.4.197</version>

</dependency>

commons-dbcp2

commons dependency for connection pooling

<dependency>

<groupId>[Link]</groupId>

<artifactId>commons-dbcp2</artifactId>

<version>2.7.0</version>

</dependency>

lombok

helps generate boilerplate code for constructors/setters/getters etc

• XML

<dependency>

<groupId>[Link]</groupId>

<artifactId>lombok</artifactId>

<version>1.18.24</version>

</dependency>

51
Configuration

Hibernate requires certain configurations to bootstrap such as DB path, driver, username,


password, etc. We are going to use the annotation-based configuration an XML-based
configuration can also be used if needed.

Create a [Link] file:

[Link] file will contain the basic configurations of the database we will read this source
to configure our hibernate session

# MySQL properties

[Link]=[Link]

[Link]=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1

[Link]=sa

[Link]=sa

# Hibernate properties

[Link]=create-drop

[Link]=[Link].H2Dialect

Configuring the Application

Create a configuration class to wire the details for hibernate and set up the session factory
etc

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

52
import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

@EnableTransactionManagement

@Configuration

@PropertySource("classpath:[Link]")

public class ExampleConfiguration {

@Autowired

private Environment env;

@Bean

public LocalSessionFactoryBean sessionFactory() {

LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();

[Link](dataSource());

[Link](

new String[]{"[Link]"});

[Link](hibernateProperties());

return sessionFactory;

@Bean

53
public DataSource dataSource() {

BasicDataSource dataSource = new BasicDataSource();

[Link]([Link]("[Link]"));

[Link]([Link]("[Link]"));

[Link]([Link]("[Link]"));

[Link]([Link]("[Link]"));

return dataSource;

@Bean

public PlatformTransactionManager hibernateTransactionManager() {

HibernateTransactionManager transactionManager

= new HibernateTransactionManager();

[Link](sessionFactory().getObject());

return transactionManager;

private final Properties hibernateProperties() {

Properties hibernateProperties = new Properties();

[Link](

"[Link]", [Link]("[Link]"));

[Link](

"[Link]", [Link]("[Link]"));

return hibernateProperties;

model class for the entity/table

• Java

54
package [Link];

import [Link];

import [Link];

import [Link];

import [Link].*;

@AllArgsConstructor

@NoArgsConstructor

@Data

@Entity

@Table(name = "user")

public class User {

@Id

@GeneratedValue(strategy = [Link])

@Column(name = "id")

private int id;

@Column(name = "first_name")

private String firstName;

@Column(name = "last_name")

private String lastName;

55
Repository class

The persistence layer to persist the model in the database

• Java

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

@Repository

public class UserRepository {

@Autowired

private SessionFactory sessionFactory;

public void addUser(User user) {

[Link]().save(user);

public User getUsers(int id) {

return [Link]().get([Link], id);

Service class

service class to interact with the repository and persist items

56
• Java

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

@Service

@RequiredArgsConstructor

public class UserService {

@Autowired

private final UserRepository userRepository;

@Transactional

public void addUser(User user) {

[Link](user);

@Transactional

public User getUser(int id) {

57
return [Link](id);

Application class

This is the entry point of the application, we need to wire this configuration to the application
context.

package example;

import [Link];

import [Link];

import [Link];

public class ExampleApplication {

public static void main(String[] args) {

[Link]("Starting application");

AnnotationConfigApplicationContext context =

new AnnotationConfigApplicationContext([Link]);

UserService userService = [Link]([Link]);

// add user to the repo

[Link](new User(1, "john", "doe"));

// search for the user in the repo

User user = [Link](1);

[Link]([Link]());

58
}

Output:

Hibernate: drop table user if exists

Hibernate: create table user (id integer generated by default as identity, first_name
varchar(255), last_name varchar(255), primary key (id))

Oct 17, 2022 3:44:14 PM


[Link] initiateService

INFO: HHH000490: Using JtaPlatform implementation:


[[Link]

ibernate: insert into user (id, first_name, last_name) values (null, ?, ?)

Hibernate: select user0_.id as id1_0_0_, user0_.first_name as first_na2_0_0_,


user0_.last_name as last_nam3_0_0_ from user user0_ where user0_.id=?

User(id=1, firstName=john, lastName=doe)

59
Package Structure :

4.4. HYBERNATE 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.

60
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 Hibernates 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 = [Link](hql);

List results = [Link]();

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

String hql = "FROM [Link]";

Query query = [Link](hql);

List results = [Link]();

AS Clause

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

String hql = "FROM Employee AS E";

Query query = [Link](hql);

List results = [Link]();

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 = [Link](hql);

61
List results = [Link]();

SELECT Clause

The SELECT clause provides more control over the result set then 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 [Link] FROM Employee E";

Query query = [Link](hql);

List results = [Link]();

It is notable here that [Link] 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 [Link] = 10";

Query query = [Link](hql);

List results = [Link]();

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 [Link] > 10 ORDER BY [Link] DESC";

Query query = [Link](hql);

List results = [Link]();

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 [Link] > 10 " +

62
"ORDER BY [Link] DESC, [Link] DESC ";

Query query = [Link](hql);

List results = [Link]();

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([Link]), [Link] FROM Employee E " +

"GROUP BY [Link]";

Query query = [Link](hql);

List results = [Link]();

HYbernate Criteria Query:

HCQL (Hibernate Criteria Query Language)

1. Hibernate Criteria Query Language

2. Criteria Interface

3. Restrictions class

4. Examples of HCQL

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.

Advantage of HCQL

The HCQL provides methods to add criteria, so it is easy for the java programmer to add
criteria. The java programmer is able to add many criteria on a query.

63
Criteria Interface

The Criteria interface provides many methods to specify criteria. The object of Criteria can be
obtained by calling the create Criteria() method of Session interface.

The commonly used methods of Criteria interface are as follows:

1. public Criteria add(Criterion c) is used to add restrictions.

2. public Criteria addOrder(Order o) specifies ordering.

3. public Criteria setFirstResult(int first Result) specifies the first number of record to be
retrieved.

4. public Criteria somersault(int total Result) specifies the total number of records to be
retrieved.

5. public List list() returns list containing object.

6. public Criteria set Projection(Projection projection) specifies the projection.

Restrictions class

Restrictions class provides methods that can be used as Criterion. The commonly used methods
of Restrictions class are as follows:

1. public static SimpleExpression lt(String propertyName,Object value) sets the less


than constraint to the given property.

2. public static SimpleExpression le(String propertyName,Object value) sets the less than
or equal constraint to the given property.

3. public static SimpleExpression gt(String propertyName,Object value) sets the greater


than constraint to the given property.

4. public static SimpleExpression ge(String propertyName,Object value) sets the greater


than or equal than constraint to the given property.

5. public static SimpleExpression ne(String propertyName,Object value) sets the not


equal constraint to the given property.

6. public static SimpleExpression eq(String propertyName,Object value) sets


the equal constraint to the given property.

64
7. public static Criterion between(String propertyName, Object low, Object high) sets
the between constraint.

8. public static SimpleExpression like(String propertyName, Object value) sets


the like constraint to the given property.

Order class

The Order class represents an order. The commonly used methods of Restrictions class are as
follows:

1. public static Order asc(String propertyName) applies the ascending order on the basis
of given property.

2. public static Order desc(String propertyName) applies the descending order on the
basis of given property.

Example of HCQL to get all the records

1. Crietria c=[Link]([Link]);//passing Class class argument

2. List list=[Link]();

Example of HCQL to get the 10th to 20th record

1. Crietria c=[Link]([Link]);

2. [Link](10);

3. [Link](20);

4. List list=[Link]();

Example of HCQL to get the records whose salary is greater than 10000

1. Crietria c=[Link]([Link]);

2. [Link]([Link]("salary",10000));//salary is the propertyname

3. List list=[Link]();

65
Example of HCQL to get the records in ascending order on the basis of salary

1. Crietria c=[Link]([Link]);

2. [Link]([Link]("salary"));

3. List list=[Link]();

HCQL with Projection

We can fetch data of a particular column by projection such as name etc. Let's see the simple
example of projection that prints data of NAME column of the table only.

1. Criteria c=[Link]([Link]);

2. [Link]([Link]("name"));

3. List list=[Link]();

Mapping Types :

The main basic types of mapping are:

1. Primitive Types

2. Date and Time Types

3. Binary and Large Object Types

4. JDK-related Types

So, let us discuss each of the above 4 listed mapping types in detail as follows:

A. Primitive Types

These types of mapping have data types defined as “integer”, “character”, “float”, “string”,
“double”, “Boolean”, “short”, “long” etc. These are present in hibernate framework to map
java data type to RDBMS data type.

Mapping Type Java Type ANSI SQL Type

integer int or [Link] INTEGER

66
Mapping Type Java Type ANSI SQL Type

character [Link] CHAR(1)

float float or [Link] FLOAT

string [Link] VARCHAR

double double or [Link] DOUBLE

boolean boolean or [Link] BIT

short short or [Link] SMALLINT

long long or [Link] BIGINT

byte byte or [Link] TINYINT

big_decimal [Link] NUMERIC

B. Date and Time

These are “date”, “time”, “calendar”, “timestamp” etc. Like primitive we have these date
and time datatype mappings.

67
Mapping type Java type ANSI SQL Type

date [Link] or [Link] DATE

time [Link] or [Link] TIME

calendar [Link] TIMESTAMP

timestamp [Link] or [Link] TIMESTAMP

calendar_date [Link] DATE

C. Binary and large objects

These types are “clob”, “blob”, “binary”, “text” etc. Clob and blob data types are present to
maintain the data type mapping of large objects like images and videos.

Mapping
type Java type ANSI SQL Type

clob [Link] CLOB

blob [Link] BLOB

VARBINARY (or
binary byte[] BLOB)

68
Mapping
type Java type ANSI SQL Type

text [Link] CLOB

any Java class that implements VARBINARY (or


serializable [Link] BLOB)

D. JDK linked

Some of the mappings for objects which lie beyond the reach of the previous type of
mappings are included in this category. These are “class”, “locale”, “currency”,
“timezone”.

Mapping type Java type ANSI SQL Type

class [Link] VARCHAR

locale [Link] VARCHAR

currency [Link] VARCHAR

timezone [Link] VARCHAR

4.5. ANNOTATIONS :

Generally, in hibernate, we use XML mapping files for converting our POJO classes data to
database data and vice-versa. But using XML becomes a little confusing so, in replacement
of using XML, we use annotations inside our POJO classes directly to declare the changes.
Also using annotations inside out POJO classes makes things simple to remember and easy
to use. Annotation is a powerful method of providing metadata for the database tables and

69
also it gives brief information about the database table structure and also POJO classes
simultaneously.

Setting up the Hibernate Annotations Project

It’s recommended to set up the Maven project for hibernate because it becomes easy to
copy-paste dependency from the official Maven repository into your [Link].

Step 1: Create Maven Project (Eclipse)

Go to next and name a project and click to finish.

Step 2: Add the dependency to the [Link] file

After setting up a maven project, by default, you get a [Link] file which is a dependency
file. POM stands for project object model, which allows us to add or remove dependency
from 1 location. Now, add hibernate and MySQL dependency to use annotations to create a
table and to use HQL(hibernate query language).

Step 3: Add [Link] file for database parameters

We use the [Link] file to provide all related database parameters like database
username, password, localhost, etc. Make sure you make the [Link] inside
the resource folder

[Link]

Step 4: Add POJO and main classes for working with the functionality

Here are some annotations used in our POJO specifically for hibernate-

Annotations Use of annotations

@Entity Used for declaring any POJO class as an entity for a database

Used to change table details, some of the attributes are-


@Table

70
Annotations Use of annotations

• name – override the table name

• schema

• catalogue

• enforce unique constraints

Step 4: Add POJO and main classes for working with the functionality

Here are some annotations used in our POJO specifically for hibernate-

Annotations Use of annotations

@Entity Used for declaring any POJO class as an entity for a database

Used to change table details, some of the attributes are-

• name – override the table name

• schema

• catalogue

@Table • enforce unique constraints

Used for declaring a primary key inside our POJO class


@Id

Hibernate automatically generate the values with reference to the


@GeneratedValue internal sequence and we don’t need to set the values manually.

71
It is used to specify column mappings. It means if in case we don’t
need the name of the column that we declare in POJO but we need
to refer to that entity you can change the name for the database
table. Some attributes are-

• Name – We can change the name of the entity for the


database

• length – the size of the column mostly used in strings

• unique – the column is marked for containing only


unique values

• nullable – The column values should not be null. It’s


@Column
marked as NOT

@Transient Tells the hibernate, not to add this particular column

This annotation is used to format the date for storing in the


@Temporal database

Used to tell hibernate that it’s a large object and is not a simple
@Lob object

This annotation will tell hibernate to OrderBy as we do in SQL.

For example – we need to order by student firstname in ascending


order

@OrderBy @OrderBy(“firstname asc”)

These are some annotations that are mostly used in order to work with hibernate.

72
4.6. NATIVE SQL :

You can use native SQL to express database queries if you want to utilize database-specific
features such as query hints or the CONNECT keyword in Oracle. Hibernate 3.x allows you to
specify handwritten SQL, including stored procedures, for all create, update, delete, and load
operations.

Your application will create a native SQL query from the session with
the createSQLQuery() method on the Session interface −

public SQLQuery createSQLQuery(String sqlString) throws HibernateException

After you pass a string containing the SQL query to the createSQLQuery() method, you can
associate the SQL result with either an existing Hibernate entity, a join, or a scalar result using
addEntity(), addJoin(), and addScalar() methods respectively.

Scalar Queries

The most basic SQL query is to get a list of scalars (values) from one or more tables. Following
is the syntax for using native SQL for scalar values

String sql = "SELECT first_name, salary FROM EMPLOYEE";

SQLQuery query = [Link](sql);

[Link](Criteria.ALIAS_TO_ENTITY_MAP);

List results = [Link]();

Entity Queries

The above queries were all about returning scalar values, basically returning the "raw" values
from the result set. Following is the syntax to get entity objects as a whole from a native sql
query via addEntity().

String sql = "SELECT * FROM EMPLOYEE";

SQLQuery query = [Link](sql);

[Link]([Link]);

List results = [Link]();

73
Named SQL Queries

Following is the syntax to get entity objects from a native sql query via addEntity() and using
named SQL query.

String sql = "SELECT * FROM EMPLOYEE WHERE id = :employee_id";

SQLQuery query = [Link](sql);

[Link]([Link]);

[Link]("employee_id", 10);

List results = [Link]();

Native SQL Example

Consider the following POJO class −

public class Employee {

private int id;

private String firstName;

private String lastName;

private int salary;

public Employee() {}

public Employee(String fname, String lname, int salary) {

[Link] = fname;

[Link] = lname;

[Link] = salary;

public int getId() {

return id;

74
public void setId( int id ) {

[Link] = id;

public String getFirstName() {

return firstName;

public void setFirstName( String first_name ) {

[Link] = first_name;

public String getLastName() {

return lastName;

public void setLastName( String last_name ) {

[Link] = last_name;

public int getSalary() {

return salary;

public void setSalary( int salary ) {

[Link] = salary;

75
}}

Let us create the following EMPLOYEE table to store Employee objects −

create table EMPLOYEE (

id INT NOT NULL auto_increment,

first_name VARCHAR(20) default NULL,

last_name VARCHAR(20) default NULL,

salary INT default NULL,

PRIMARY KEY (id)

);

Following will be mapping file −

<?xml version = "1.0" encoding = "utf-8"?>

<!DOCTYPE hibernate-mapping PUBLIC

"-//Hibernate/Hibernate Mapping DTD//EN"

"[Link]

<hibernate-mapping>

<class name = "Employee" table = "EMPLOYEE">

<meta attribute = "class-description">

This class contains the employee detail.

</meta>

<id name = "id" type = "int" column = "id">

<generator class="native"/>

</id>

76
<property name = "firstName" column = "first_name" type = "string"/>

<property name = "lastName" column = "last_name" type = "string"/>

<property name = "salary" column = "salary" type = "int"/>

</class>

</hibernate-mapping>

Finally, we will create our application class with the main() method to run the application where
we will use Native SQL queries −

import [Link].*;

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class ManageEmployee {

private static SessionFactory factory;

public static void main(String[] args) {

try {

factory = new Configuration().configure().buildSessionFactory();

} catch (Throwable ex) {

[Link]("Failed to create sessionFactory object." + ex);

77
throw new ExceptionInInitializerError(ex);

ManageEmployee ME = new ManageEmployee();

/* Add few employee records in database */

Integer empID1 = [Link]("Zara", "Ali", 2000);

Integer empID2 = [Link]("Daisy", "Das", 5000);

Integer empID3 = [Link]("John", "Paul", 5000);

Integer empID4 = [Link]("Mohd", "Yasee", 3000);

/* List down employees and their salary using Scalar Query */

[Link]();

/* List down complete employees information using Entity Query */

[Link]();

/* Method to CREATE an employee in the database */

public Integer addEmployee(String fname, String lname, int salary){

Session session = [Link]();

Transaction tx = null;

Integer employeeID = null;

try {

tx = [Link]();

Employee employee = new Employee(fname, lname, salary);

78
employeeID = (Integer) [Link](employee);

[Link]();

} catch (HibernateException e) {

if (tx!=null) [Link]();

[Link]();

} finally {

[Link]();

return employeeID;

/* Method to READ all the employees using Scalar Query */

public void listEmployeesScalar( ){

Session session = [Link]();

Transaction tx = null;

try {

tx = [Link]();

String sql = "SELECT first_name, salary FROM EMPLOYEE";

SQLQuery query = [Link](sql);

[Link](Criteria.ALIAS_TO_ENTITY_MAP);

List data = [Link]();

for(Object object : data) {

Map row = (Map)object;

[Link]("First Name: " + [Link]("first_name"));

79
[Link](", Salary: " + [Link]("salary"));

[Link]();

} catch (HibernateException e) {

if (tx!=null) [Link]();

[Link]();

} finally {

[Link]();

/* Method to READ all the employees using Entity Query */

public void listEmployeesEntity( ){

Session session = [Link]();

Transaction tx = null;

try {

tx = [Link]();

String sql = "SELECT * FROM EMPLOYEE";

SQLQuery query = [Link](sql);

[Link]([Link]);

List employees = [Link]();

for (Iterator iterator = [Link](); [Link]();){

Employee employee = (Employee) [Link]();

[Link]("First Name: " + [Link]());

[Link](" Last Name: " + [Link]());

80
[Link](" Salary: " + [Link]());

[Link]();

} catch (HibernateException e) {

if (tx!=null) [Link]();

[Link]();

} finally {

[Link]();

Compilation and Execution

Here are the steps to compile and run the above mentioned application. Make sure, you have
set PATH and CLASSPATH appropriately before proceeding for the compilation and
execution.

• Create [Link] configuration file as explained in configuration


chapter.

• Create [Link] mapping file as shown above.

• Create [Link] source file as shown above and compile it.

• Create [Link] source file as shown above and compile it.

• Execute ManageEmployee binary to run the program

• You would get the following result, and records would be created in the EMPLOYEE
table.

• $java ManageEmployee

• .......VARIOUS LOG MESSAGES WILL DISPLAY HERE........

• First Name: Zara, Salary: 2000

81
• First Name: Daisy, Salary: 5000

• First Name: John, Salary: 5000

• First Name: Mohd, Salary: 3000

• First Name: Zara Last Name: Ali Salary: 2000

• First Name: Daisy Last Name: Das Salary: 5000

• First Name: John Last Name: Paul Salary: 5000

• First Name: Mohd Last Name: Yasee Salary: 3000

• If you check your EMPLOYEE table, it should have the following records −

• mysql> select * from EMPLOYEE;

• +----+------------+-----------+--------+

• | id | first_name | last_name | salary |

• +----+------------+-----------+--------+

• | 26 | Zara | Ali | 2000 |

• | 27 | Daisy | Das | 5000 |

• | 28 | John | Paul | 5000 |

• | 29 | Mohd | Yasee | 3000 |

• +----+------------+-----------+--------+

• 4 rows in set (0.00 sec)

• mysql>

4.7. SUMMARY:

This module brings about the various ways in which hibernate feature can be utilized in
[Link] architecture of hibernate is explained clearly and then the implementation of MVC is
explained. Then the several types of annotations are explained. The native SQL statements that
can be used with hibernate are also explained.

82
4.8. SELF-STUDY QUESTIONS:

[Link] the architecture of hibernate

2. Explain the implementation of MVC with hibernate in Java

3. Explain the different types of annotations in hibernate

[Link] the different native SQL statements that can be used with hibernate

4.9. SUGGESTED READING :

1. Java Complete Reference, Seventh Edition, -Herbert Schildt

83

You might also like