AdvJava PG Hibernate Unit V

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 31

UNIT V HIBERNATE

Object Relational Mapping(ORM):Any persistence solution that maps objects to tables in


database is called as ORM (Object Relational Mapping) solution. Hibernate is one such ORM
solution that sits in between Java applications and database as shown in the following figure.

Fig. Java and Hibernate

From the above figure, Java applications use Hibernate to map Java objects to Tables in relational
database.

Features of Hibernate ORM Solution


Hibernate ORM solution provides us with a clean API for persisting data objects.
Provides a dialect (Hibernate Query Language aka HQL) to specify the SQL operations.
Provides an XML based mapping tool to map the Java bean properties to the columns in
relational tables.

Advantages of Hibernate ORM Solution


Allows application developers to manage the Java objects and abstracts all the SQL
operations from the developer.

It’s a light weight ORM solution and doesn’t even need a application server or container to run
the applications.
Offer loose coupling of Javabeans with the underlying tables though the use of XML as the
medium of communication.
Consumes less resources there by improves the overall performance of the application.
Offers significant amount of flexibility in designing persistence applications.
Typical Hibernate Components
Hibernate commonly uses two XML files for persisting data in Java objects.
One is the user defined XML file that contains all the mapping information.
A standard hibernate.cfg.xml file that contains all the database configuration information
along with the locations of user defined mapping XML in step 1.

Mapping Beans to Tables


This is an example shows how to map the JavaBean properties to the columns in a table.
Following figure shows the mapping diagram.

(Customer.java) Simple Java Bean


package hibernate.example1;

public class Customer {

private String firstName;

private String lastName;

private int ssn;

private String addressLine1;

private String city;

private String state;

private String country;

public String getFirstName() {

return firstName;

public void setFirstName(String firstName) {

this.firstName = firstName;
}

public String getLastName() {

return lastName;

public void setLastName(String lastNamme) {

this.lastName = lastNamme;

public int getSsn() {

return ssn;

public void setSsn(int ssn) {

this.ssn = ssn;

public String getAddressLine1() {

return addressLine1;

public void setAddressLine1(String addressLine1) {

this.addressLine1 = addressLine1;

public String getCity() {

return city;

public void setCity(String city) {

this.city = city;

public String getCountry() {

return country;

public void setCountry(String country) {

this.country = country;

public String getState() {

return state;
}

public void setState(String state) {

this.state = state;

(example1.hbm.xml) Mapping document

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC

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

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

<class name="hibernate.example1.Customer"
table="CUSTOMERS1"> <id name="ssn">

<generator class="assigned" />

</id>

<property name="firstName" column="FIRST_NAME"/>

<property name="lastName" column="LAST_NAME"/>

<property name="addressLine1" column="ADDRESS_LINE"/>

<property name="city" column="CITY"/>

<property name="state" column="STATE"/>

<property name="country" column="COUNTRY"/>

</class>

</hibernate-mapping>

This mapping file defines a class element that tells Hibernate to map Customer bean to
CUSTOMERS1 table using the following line
<class name="hibernate.example1.Customer" table="CUSTOMERS1">

Specifies the bean properties to the column names. The only tricky part is the id element. Every
table that we map using the class element must have a primary key column and id element
must be used to map a bean property to the primary key.
Configuring Hibernate
Hibernate uses a class called SessionFactory for persisting and loading data objects to and
from the database. Hibernate uses Configuration class to configure the session factory.
SessionFactory can be configured using XML, Property files and even programmatically.

Associations
Associations basically indicate that one class retains the relationship to another class over an
extended period of time. In a Customer-Address example, an address is associated with a
customer.
Moreover associations can be unidirectional or bidirectional.If the association is unidirectional
from A to B, then A can see changes made to B and not vice-versa.With a bidirectional
association, both A and B can see each others changes. The following figure shows both
unidirectional and bidirectional associations.

Fig .Unidirectional and Bi-directional associations

Associations are basically represented in the following four ways:

One-to-One Association
One-to-Many association
Many-to-One association
Many-to-Many association

Many-to-One Association
Unidirectional Many-to-One/One-to-many Association
The simple example for this association is multiple books belonging to the same publisher. At the same time
if only the Books should be able to see the changes made to the publisher, it becomes unidirectional.

BOOKS PUBLISHERS
BOOK_ID PUB_ID AUTHOR TITLE PUB_ID PUB_NAME
101 123 123
102 123

The class definition for Publisher class will be as shown below:


<class name="hibernate.example4.Publisher" table="PUBLISHERS4">
<id name="publisherId" column="PUB_ID">

<generator class="increment" />

</id>

<property name="publisherName" column="PUB_NAME" />

</class>

The above definition maps publisherId and publisherName to the respective columns in the
PUBLISHERS table. Now look at the class definition for the Book class.
<class name="hibernate.example4.Book" table="BOOKS4">

<id name="bookId" column="BOOK_ID">

<generator class="increment" />

</id>

<many-to-one name="publisher" column="PUB_ID" />

<property name="author" column="AUTHOR" />

<property name="title" column="TITLE" />

</class>

In the above definition, the many-to-one element tells hibernate to use the PUBLISHERS
primary key as the foreign key in the BOOKS table. The PUB_ID column in BOOKS table will
now have the same value as the PUB_ID column in the PUBLISHERS table.
Bidirectional Many-to-one/One-to-Many
In this case, the publisher should have the knowledge of all the books it published. Therefore,
the publisher class should have a collection property for books as shown below:
public class Publisher {

int publisherId;

String publisherName;

Set books;

// Getter and Setters

void addBook(Book book){

books.add(book);

book.setPublisher(this);

In the addBook() utility method. If it is tried to associate a book to a publisher, then it is just to update
the record in the books table to set the publisher using the following update statement.

update BOOKS set PUB_ID=? where BOOK_ID=?


Both one-to-many and many-to-one relationships work just the same way.

One-to-One Association
In this association, one object (record in one table) should be associated with one and only one
object (record in another table). For example, a book can only be associated with one publisher.
This association can be implemented in two ways.
i)Using Foreign Key
ii)Using Primary Key

Unidirectional Foreign Key Association


In this case, a one-to-one association is derived from a many-to-one relationship by setting
the unique property to true for the PUB_ID column in the BOOKS table. The PUB_ID then
becomes the foreign key to the PUBLISHERS table primary key. For instance let’s say we
have the following tables:

BOOKS PUBLISHERS
BOOK_ID PUB_ID AUTHOR TITLE PUB_ID PUB_NAME
101 123 123
102 123
From the above table, a one-to-one relationship can be obtained from a many-to-one
relationship by eliminating the duplicate foreign key (PUB_ID) in the books table. It is
instructed to hibernate by simply setting the unique attribute to true for the PUB_ID in the
class definition for book as shown below:

<class name="hibernate.example5.Book" table="BOOKS5">

<id name="bookId" column="BOOK_ID">

<generator class="increment" />

</id>

<many-to-one name="publisher" column="PUB_ID" unique="true" />

<property name="author" column="AUTHOR" />

<property name="title" column="TITLE" />

</class>

The class definition for Publisher will remain the same as shown below:
<class name="hibernate.example5.Publisher" table="PUBLISHERS5">
<id name="publisherId" column="PUB_ID">

<generator class="increment" />

</id>

<property name="publisherName" column="PUB_NAME" />

</class>

When Hibernate generates the DDL for the tables, it adds a foreign key constraint to the
PUB_ID in the Books table as shown
With the above relationship, if it is tried to add more than one book to the same publisher it
will add the first book and then throws an exception.
Bidirectional Foreign Key Association
Making this association bidirectional is nothing but having the publisher access the book
information. The only difference is that in this case, it has to be just one book. Firstly, we need
to add the book reference in the Publisher class as shown below:

public class Publisher {

int publisherId;

String publisherName;

Book book;

// Getter and Setters for book

Secondly, the class definition for the Publisher will look as shown below:
<class name="hibernate.example5.Publisher" table="PUBLISHERS5">

<id name="publisherId" column="PUB_ID">

<generator class="increment" />

</id>

<property name="publisherName" column="PUB_NAME" />

<one-to-one name="book" class="hibernate.example5.Book"

property-ref="publisher" />

</class>

From the above definition, it is added a one-to-one mapping of the book to the publisher
using the property-ref attribute. This tells Hibernate that the book association in Publisher
is the reverse of publisher association in Book.

Unidirectional Primary Key Association


With this type of association, both the books and the publishers table will have the same
primary key as shown in the following figure.
From the above figure, both the BOOK_ID and PUB_ID must always be the same. This way
the foreign key PUB_ID can be completely deleted from the books table. It is to tell hibernate
to use PUB_ID in the publisher table as both primary key and also the foreign key of the
BOOK_ID in the books table. Only then, hibernate will insert same value in both the tables.
This is done using the constrained=true attribute as shown in the following publisher class
definition:
<class name="hibernate.example5.Publisher" table="PUBLISHERS6">

<id name="publisherId" column="PUB_ID">

<generator class="foreign">

<param name="property">book</param>

</generator>

</id>

<property name="publisherName" column="PUB_NAME" />

<one-to-one name="book" constrained="true" />

</class>

The constraint=true attribute tells hibernate that there is a foreign key constraint on the
primary key of the publisher table.
A special generator named foreign must be used which tells hibernate to use the value of the
primary key on the books table as the primary key value in the publishers table.

Bidirectional Primary Key Association


Making the previous association as bidirectional is very simple. It is to add a publisher
property in the book object using a one-to-one association as shown below:

<class name="hibernate.example5.Book" table="BOOKS6">

<id name="bookId" column="BOOK_ID">

<generator class="increment" />

</id>

<property name="author" column="AUTHOR" />

<property name="title" column="TITLE" />

<one-to-one name=”publisher”
class=”hibernate.example5.Publisher”/> </class>
The above tells hibernate to also retrieve the publisher while retrieving the book.

Many-to-Many Association
The classical example for this association is the one between Topics and Subscriptions.

Implementing a many-to-many relationship requires an additional table called the link table.
There is no way you can implement this scenario using two tables. The link table basically
contains the primary keys of both the tables as shown in the following diagram:

Unidirectional Many-to-Many association


In this case, the Topic object will define a collection of subscriber objects as shown below:
public class Topic{

int topicid;

String topicName;

Set subscribers;

// Getters and Setters

}
The subscriber class will define a collection of topics objects as shown below:
public class Subscriber{

int sid;

String name;

Set topics;

// Getters and Setters

With unidirectional association, a topic will have the knowledge of all the subscribers and not vice-versa.

In this case, the class definition for Topic class will look as shown below:
<class name="hibernate.example6.Topic" table="TOPICS6">

<id name="topicId" column="TOPIC_ID">

<generator class="native" />

</id>

<property name="topicName" column="TOPIC_NAME" />

<set name="subscribers" table="TOPIC_SUB6">

<key column="TOPIC_ID" />

<many-to-many column="SUB_ID"

class="hibernate.example6.Subscriber" />

</set>

</class>

From the above definition, the set element tells hibernate to insert TOPIC_ID from TOPICS6 table
and SUB_ID from SUBSCRIBERS6 table into the link table TOPIC_SUB6 when the association is
made.

Following is the class definition for subscriber class. This class will not have the subscribers
property defined as we should not allow subscribers to access topics.
<class name="hibernate.example6.Subscriber" table="SUBSCRIBERS6">
<id name="sid" column="SUB_ID">

<generator class="increment" />

</id>

<property name="name" column="NAME" />

</class>
Bidirectional Many-to-Many association
In this case, to update the class definition of the subscriber it is to include the topics property
as a set element as shown below:
<class name="hibernate.example6.Subscriber"
table="SUBSCRIBERS6"> <id name="sid" column="SUB_ID">

<generator class="increment" />

</id>

<property name="name" column="NAME" />

<set name="topics" table="TOPIC_SUB" inverse=”true” >

<key column="SUB_ID" />

<many-to-many column="TOPIC_ID" class="hibernate.example6.Subscriber" />

</set>

</class>

From the above definition, this is simply the reverse of the subscribers property in the Topic
class definition. However, it is to add the inverse=”true” attribute to tell hibernate to
synchronize both the ends of the association .

Polymorphic associations:
Polymorphic association is an association in which a child object is referenced by a parent class
reference. The parent component can be a concrete parent class, or an abstract class or even an
interface. With polymorphic associations following are the two cases we need to look at:

Mapping a inheritance hierarchy to tables


Write queries that return all the child objects that match the parent interface.
From the above figure, the shopping cart object references a product
object which can be either be object of Book or Computer class.
Approaches mapping hierarchy to the Database tables:
There are three approaches with which we can map the above hierarchy
to the database tables.

Table per concrete class


Table per hierarchy
Table per child class

Table per Concrete class


In this approach, as the name suggests it is used one table per concrete
class in the hierarchy. In our case Book and Computer are two concrete
classes of abstract Product class. Therefore, Hibernate will create one
table for each subclass with columns for all the properties in the sub
classes including the inherited properties as shown below

From the above two tables, hibernate will create PRODUCT_ID and
SELLER columns for the inherited properties in each of the table. It’s
important to note that hibernate will not create a table for the Product class
as it is abstract.

A column that defines the type of the subclass, for instance


PRODUCT_TYPE whose value identifies the type of the subclass
object (Book or Computer)
A column that stores the primary keys of both the Book and Computer
table some thing like ITEM_ID. This is not a foreign key but can be
thought of as a composite foreign key since it holds to both the
subclass tables primary keys.

The ShoppingCart element should use the element any to tell hibernate
about the two columns as shown below:
<any name="product" meta-type="string" id-
type="int" cascade="save-update"> <meta-
value value="BOOK"
class="hibernate.example7.Book" /> <meta-
value value="COMPUTER"
class="hibernate.example7.Computer" />
<column name="PRODUCT_TYPE" />

<column name="ITEM_ID" />

</any>

From the above mapping, the any element defined two columns is as
shown below:
<column name="PRODUCT_TYPE" />

<column name="ITEM_ID" />

The PRODUCT_TYPE column contains two values to identify two sub


classes.It is to tell Hibernate what possible values that it can have
and also the type of values.It is to use meta-value element for the
former and meta-type attribute for the later. The id-type attribute
specifies the column type for ITEM_ID column.
(Product.java) An abstract product class.

package hibernate.example7;

public abstract class Product {

int productId;

String seller;

public abstract int getProductId();

public abstract void setProductId(int productId);

public abstract String getSeller();

public abstract void setSeller(String seller);

(Book.java) A simple class


package hibernate.example7;

public class Book extends Product {

String isbn;

String author;

String title;

String publisher;

public String getTitle() {

return title;

public void setTitle(String title) {

this.title = title;

public String getAuthor() {

return author;

public void setAuthor(String author) {

this.author = author;

public String getIsbn() {

return isbn;

public void setIsbn(String isbn) {

this.isbn = isbn;

public String getPublisher() {

return publisher;
}

public void setPublisher(String publisher) {

this.publisher = publisher;

public int getProductId() {

return productId;

public void setProductId(int productId) {

this.productId = productId;

public String getSeller() {

return seller;

public void setSeller(String seller) {

this.seller = seller;

(Computer.java) A simple class

package hibernate.example7;

public class Computer extends Product {

String processor;

int ramSize;

String os;

String type;

public String getOs() {


return os;

public void setOs(String os) {

this.os = os;

public String getProcessor() {

return processor;

public void setProcessor(String processor) {

this.processor = processor;

public int getRamSize() {

return ramSize;

public void setRamSize(int ramSize) {

this.ramSize = ramSize;

public String getType() {

return type;

public void setType(String type) {

this.type = type;

public int getProductId() {

return productId;

public void setProductId(int productId) {

this.productId = productId;

}
public String getSeller() {

return seller;

public void setSeller(String seller) {

this.seller = seller;

(ShoppingCart.java) A simple class


package hibernate.example7;

public class ShoppingCart {

int clientId;

Product product;

public int getClientId() {

return clientId;

public void setClientId(int clientId) {

this.clientId = clientId;

public Product getProduct() {

return product;

public void setProduct(Product product) {

this.product = product;

}
The above code represent the JavaBean classes for Product, Book,
ShoppingCart and Computer.

(example7.hbm.xml) Class definitions

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC

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

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

<class name="hibernate.example7.Book" table="BOOK7"

polymorphism="implicit">

<id name="productId" column="BOOK_ID">

<generator class="increment" />

</id>

<property name="seller" column="SELLER" />

<property name="author" column="AUTHOR" />

<property name="title" column="TITLE" />

<property name="publisher" column="PUBLISHER" />

</class>

<class name="hibernate.example7.Computer" table="COMPUTERS7"

polymorphism="implicit">

<id name="productId" column="PRODUCT_ID">

<generator class="increment" />

</id>

<property name="seller" column="SELLER" />

<property name="processor" column="PROCESSOR" />

<property name="ramSize" column="RAM" />

<property name="os" column="OS" />


<property name="type" column="TYPE" />

</class>
<class
name="hibernate.example7.Shopping
Cart" table="SHOPPINGCART7"> <id
name="clientId"
column="PRODUCT_ID">

<generator class="increment" />

</id>

<any name="product" meta-type="string" id-type="int"

cascade="save-update">

<meta-value value="BOOK" class="hibernate.example7.Book" />

<meta-value value="COMPUTER"

class="hibernate.example7.Computer" />

<column name="PRODUCT_TYPE" />

<column name="ITEM_ID" />

</any>

</class>

</hibernate-mapping>

Notice the class mappings for Book and Computer. They simply map their
respective properties to columns in tables like we did in the very first example.
The only difference is that it is to add polymorphism=”true” attribute to tell
hibernate that their associations are polymorphic in nature. Also note that both
the classes uses the inherited productId as the primary key.

The following code creates a Book object and associates with a


ShoppingCart polymorphically.
session.beginTransaction();

Book b = new Book();

b.setAuthor("James");

b.setTitle("J2EE");
b.setPublisher("Pub Inc");

b.setSeller("JC Inc");

ShoppingCart cart = new ShoppingCart();

cart.setProduct(b);

session.save(cart);

session.getTransaction().commit();

The above code will insert one record in the books table and one in the
shoppingcart table. Now, we can use the following code to retrieve the
shopping cart which also retrieves the book object.
ShoppingCart c1 =
(ShoppingCart)session.get(ShoppingCart.cl
ass,new Integer(1)); Book b =
(Book)c1.getProduct();

This approach though works well is very seldom used due to its inherent
complexity. Use this technique when require polymorphic association is
not required.

Table per Hierarchy


In this approach, it is used as one table to map the entire hierarchy that
includes Product, Book and Computer classes. This one table contains
columns for all the properties defined in all the classes as shown below:
The above table now has all the columns. It is the challenge that how
does hibernate know which columns are associated with Book class and
which columns with Computer class?
The good thing is hibernate gave us the solution by asking us to use
subclass element along with the discriminator column while mapping the
class.The discriminator column tells hibernate which columns to
populate/read for the sub classes. This is why in the above table, hibernate
also created PRODUCT_TYPE column to store some unique identifiers
that tells which specific object to store or retrieve. The class definition for
the product class will be as shown below:

<class name="hibernate.example7.Product" table="PRODUCT8"

polymorphism="implicit">

<id name="productId" column="PRODUCT_ID">

<generator class="increment" />

</id>

<discriminator column="PRODUCT_TYPE" type="string" />


<subclass
name="hibernate.example7.Book"
discriminator-value="BOOK">
<property name="seller"
column="SELLER" />

<property name="author" column="AUTHOR" />

<property name="title" column="TITLE" />

<property name="publisher" column="PUBLISHER" />

</subclass>

<subclass name="hibernate.example7.Computer"

discriminator-value="COMPUTER">

<property name="seller" column="SELLER" />

<property name="processor" column="PROCESSOR" />


<property name="ramSize" column="RAM" />

<property name="os" column="OS" />

<property name="type" column="TYPE" />

</subclass>

</class>

From the above definition for the product class, it defined a discriminator
column along with two subclass elements, one for book and other for
computer class. Also note that the subclass elements specified a
discriminator values namely BOOK and COMPUTER for hibernate to
distinguish between the two.
Now, the mapping from ShoppingCart to Product can be implemented as
a one-to-one association as shown below:

<class name="example7.ShoppingCart" table="SHOPPINGCART3">

<id name="clientId" column="CLIENT_ID">

<generator class="increment" />

</id>

<many-to-one name="product" column="PRODUCT_ID" unique="true"

cascade="save-update" />

</class>

Recall that a one-to-one association can be implemented as many-to-one


association with unique=”true” attribute. The only difference is that you’ll see
just one table created in the database as shown below:

PRODUCT_ID PRODUCT_TYPE SELLER AUTHOR TITLE PUBLISHER PROCESSOR RAM OS Ty

1 BOOK ABC, INC James J2EE Apex


From the above, hibernate added BOOK as the discriminator value and
populated columns corresponding to Book. Try adding a computer to the
shopping cart and you’ll see the other columns filled with book columns
with blank values.

This is the simplest type of polymorphic association and also easy to


understand without any confusions. Moreover, this is the most efficient
way of persisting objects.

Table per Sub Class


This approach is same as table per concrete class except that hibernate
will not create columns for inherited properties as shown in the following
figure.

From the above, the following two important things are observed:
Hibernate will eliminate the columns for the inherited properties in the
Books and Computers table, and adds a primary key column.
Because of the elimination of the columns in step1, it will create a table
for the abstract class Product with columns for inherited properties.

When we persist on of the computer or book class, hibernate will insert


the book or computer related data in the books or computers table and
the inherited properties from the product class in the products table. So,
every time when adding a new product, one record will be inserted in
one of the specific tables, and one in the products table.
Now that there are three tables each with their own primary keys, hibernate will
simply use the primary keys of the sub classes to map with the super class. With this
approach,it is to tell hibernate using the

joined-subclass element as shown below. The mapping is just the same as with
subclass element.

<class name="hibernate.example7.Product" table="PRODUCT9"

polymorphism="implicit">

<id name="productId" column="PRODUCT_ID">

<generator class="increment" />

</id>

<property name="seller" column="SELLER" />

<joined-subclass
name="hibernate.example7
.Book" table="BOOKS9">
<key
column="BOOK_ID" />

<property name="seller" column="SELLER" />

<property name="author" column="AUTHOR" />

<property name="title" column="TITLE" />

<property name="publisher" column="PUBLISHER" />

</joined-subclass>

<joined-subclass
name="hibernate.example7.Computer
" table="COMPUTERS9"> <key
column="COMP_ID" />

<property name="seller" column="SELLER" />

<property name="processor" column="PROCESSOR" />

<property name="ramSize" column="RAM" />

<property name="os" column="OS" />

<property name="type" column="TYPE" />


</joined-subclass>

</class>

From the above class mapping for Product, it defined its own properties like
productId and seller and then defined the mappings for its subclasses using the
joined-subclass element. The only difference you’d notice with this element
compared to the subclass element in the previous example is that we specified the
table names highlighted in bold and defined the key column in both the subclass
tables.

Hibernate Query Language (HQL)


HQL is a query language used by Hibernate to query the persisted
objects in the tables.Hibernate will translate all the HBL queries into SQL
queries behind the scenes and fetch the objects. This will really simplify
the life of the developer than building the complex SQL queries.

Hibernate supports two important classes namely Query and Criteria to query for
objects. Either Query or Criteria class can be used for retrieving objects. In
some cases using Query is more flexible and in some other cases using
Criteria is more flexible.

Case 1: To retrieve all the Book objects from the BOOKS table.
Using Query:
Query query = session.createQuery(“from Book”);

List records = query.list();

In this case, creating the Query object from the session by specifying the
query string. With the string “from Book”, hibernate will automatically figure out
the table name based on the mappings that defined in the xml and returns all
the Book object populating all the properties with the column data. Behind the
scenes, hibernate will translate the above into the following SQL:
Select bookId, author, publisher from BOOKS;

Using Criteria
Criteria c = session.createCriteria(Book.class);

List records = c.list();

In this case, Hibernate will return all the Book objects from the BOOKS
table by just specifying the class of the objects to retrieve..

Case 2: Binding parameters at runtime.


Binding parameters at runtime allows to execute dynamic SQL statements, It
is just similar like PreparedStatement in JDBC. For example, to retrieve all the
Books authored by James

Using Query
String qs= “from Book b where b.author like :author”;

Query q = session.createQuery(qs);

q.setString(“author”,”James”);

List results = q.list();

In the above query, “:author” is the query parameter. With HQL, all the
parameters must be prefixed with a colon as shown. Based on the type of
data to be passed to the parameter, we can use the set methods defined
by the Query interface. One such method is the setString() method to set
the character data. Likewise, there are several other set methods for
passing dates, numbers etc,. The above query retrieves all the Book
objects that are authored by James.

HQL also permits using indices for parameters instead of names as


shown below:

String qs= “from Book b where b.author like ?”;

Query q = session.createQuery(qs);
q.setString(0,”James”);

List results = q.list();

String qs = “from Book b where b.author=? and b.publiser=?”;

List results = session.createQuery(qs).

setString(0,”James”).

setString(1,”Premium Publishing”).

list();

These are all the basic HQL operations that need to know. Using both
Query and Criteria interfaces you can build any complex queries for
retrieving the objects.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy