Book Image

Java Hibernate Cookbook

By : Yogesh Prajapati, Vishal Ranapariya
Book Image

Java Hibernate Cookbook

By: Yogesh Prajapati, Vishal Ranapariya

Overview of this book

This book will provide a useful hands-on guide to Hibernate to accomplish the development of a real-time Hibernate application. We will start with the basics of Hibernate, which include setting up Hibernate – the pre-requisites and multiple ways of configuring Hibernate using Java. We will then dive deep into the fundamentals of Hibernate such as SessionFactory, session, criteria, working with objects and criteria. This will help a developer have a better understanding of how Hibernate works and what needs to be done to run a Hibernate application. Moving on, we will learn how to work with annotations, associations and collections. In the final chapters, we will see explore querying, advanced Hibernate concepts and integration with other frameworks.
Table of Contents (15 chapters)
Java Hibernate Cookbook
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Transforming a result


As a developer, I love this feature, as it helps the developers to transform the returned rows to List, Map, or user-defined Bean.

How to do it...

Now we will take a look at three scenarios of the demonstration code that will convert the records returned by hibernate to List, Map, and Bean.

Here, we use the Transformers class to provide the transforming mechanism to criteria.

Scenario 1: Converting a result to List

All the demos up to this point show that if we use the criteria.list() method, the resultant data is always returned in List. However, you can still use Transformers.TO_LIST in criteria, as follows:

criteria.setResultTransformer(Transformers.TO_LIST);

This means that every row in the result will be represented as a List.

Scenario 2: Converting a result to Map

Now, let's see how to convert the resultant data in Map:

criteria.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);

This means every object from List represents Map.

Code

For example, the following code shows...