Book Image

Java Hibernate Cookbook

Book Image

Java Hibernate Cookbook

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

Creating an autogenerator column


Generally, we create a primary column with some autogenerated value. Hibernate allows us to create the same using code. Let's take a look at some methods to create a column with an autogenerated value.

How to do it…

We can create an autogenerated column in many ways, such as:

  • Using a default generation strategy

  • Using a sequence generator

  • Using a table generator

Default generation strategy

To use a default strategy for autogeneration, we will use the @GeneratedValue annotation, as follows:

@Id
@GeneratedValue
private long id;

Using the preceding code, hibernate will create a column with an autoincremental value.

By default, hibernate uses the GenerationType.AUTO strategy if no strategy is supplied; so, @GeneratedValue is equal to @GeneratedValue(strategy=GenerationType.AUTO).

Still, as it is database–specific, it's the responsibility of the database to provide a value for this column, and the same rule is applied for @GeneratedValue(strategy=GenerationType.IDENTITY)...