Hibernate Tutorial - Orgfree

1y ago
31 Views
3 Downloads
3.37 MB
150 Pages
Last View : 1d ago
Last Download : 3m ago
Upload by : Albert Barnett
Transcription

Hibernate Tutorial

HIBERNATE TUTORIALSimply Easy Learning by tutorialspoint.comtutorialspoint.com

ABOUT THE TUTORIALHibernate TutorialHibernate is a high-performance Object/Relational persistence and query service which is licensed under theopen source GNU Lesser General Public License (LGPL) and is free to download. Hibernate not only takes careof the mapping from Java classes to database tables (and from Java data types to SQL data types), but alsoprovides data query and retrieval facilities.This tutorial will teach you how to use Hibernate to develop your database based web applications in simple andeasy steps.AudienceThis tutorial is designed for Java programmers with a need to understand the Hibernate framework and API. Aftercompleting this tutorial you will find yourself at a moderate level of expertise in using Hibernate from where youcan take yourself to next levels.PrerequisitesWe assume you have good understanding of the Java programming language. A basic understanding ofrelational databases, JDBC and SQL is very helpful.Copyright & Disclaimer Notice All the contentand graphics on this tutorial are the property of tutorialspoint.com. Any content fromtutorialspoint.com or this tutorial may not be redistributed or reproduced in any way, shape, or formwithout the written permission of tutorialspoint.com. Failure to do so is a violation of copyright laws.This tutorial may contain inaccuracies or errors and tutorialspoint provides no guarantee regarding theaccuracy of the site or its contents including this tutorial. If you discover that the tutorialspoint.com siteor this tutorial content contains some errors, please contact us at webmaster@tutorialspoint.comTUTORIALS POINTSimply Easy Learning

Table of ContentHibernate Tutorial . 2Audience . 2Prerequisites . 2Copyright & Disclaimer Notice. 2ORM Overview. 8Pros and Cons of JDBC . 8Why Object Relational Mapping (ORM)? . 8What is ORM? . 9Java ORM Frameworks . 10Hibernate Overview . 11Hibernate Advantages . 11Supported Databases . 12Supported Technologies . 12Hibernate Architecture . 13Configuration Object . 14SessionFactory Object . 14Session Object . 15Transaction Object . 15Query Object . 15Criteria Object . 15Hibernate Environment . 16Downloading Hibernate:. 16Installing Hibernate . 17Hibernate Prerequisites . 17Hibernate Configuration . 18Hibernate Properties . 18Hibernate with MySQL Database . 19Hibernate Sessions . 21Session Interface Methods . 22Hibernate Persistent Class . 24A simple POJO example: . 24Hibernate Mapping Files . 26Hibernate Mapping Types . 29Primitive types . 29Date and time types . 29Binary and large object types . 30JDK-related types . 30TUTORIALS POINTSimply Easy Learning

Hibernate Examples . 31Create POJO Classes . 31Create Database Tables . 32Create Mapping Configuration File . 32Create Application Class . 33Compilation and Execution . 35Hibernate O/R Mapping . 36Collections Mappings . 36Hibernate Set Mappings . 36Define RDBMS Tables . 37Define POJO Classes . 37Define Hibernate Mapping File . 39Create Application Class . 40Compilation and Execution . 42Hibernate SortedSet Mappings . 43Define RDBMS Tables . 43Define POJO Classes . 44Define Hibernate Mapping File . 45Create Application Class . 47Compilation and Execution . 49Hibernate List Mappings . 50Define RDBMS Tables . 50Define POJO Classes . 51Define Hibernate Mapping File . 52Create Application Class . 53Compilation and Execution . 55Hibernate Bag Mappings . 57Define RDBMS Tables . 57Define POJO Classes . 57Define Hibernate Mapping File . 58Create Application Class . 60Compilation and Execution . 62Hibernate Map Mappings . 63Define RDBMS Tables . 63Define POJO Classes . 63Define Hibernate Mapping File . 65Create Application Class . 66Compilation and Execution . 68Hibernate SortedMap Mappings . 69TUTORIALS POINTSimply Easy Learning

Define RDBMS Tables . 69Define POJO Classes . 70Define Hibernate Mapping File . 71Compilation and Execution . 75Association Mappings . 76Hibernate Many-to-One Mappings . 76Define RDBMS Tables . 76Define POJO Classes . 77Define Hibernate Mapping File . 79Compilation and Execution . 82Hibernate One-to-One Mappings . 83Define RDBMS Tables . 83Define POJO Classes . 84Define Hibernate Mapping File . 86Compilation and Execution . 89Hibernate One-to-Many Mappings . 90Define RDBMS Tables . 90Define POJO Classes . 91Define Hibernate Mapping File . 92Create Application Class . 93Compilation and Execution . 95Hibernate Many-to-Many Mappings . 96Define RDBMS Tables . 97Define POJO Classes . 97Define Hibernate Mapping File . 99Create Application Class . 100Compilation and Execution . 102Component Mappings . 103Hibernate Component Mappings. 103Define RDBMS Tables . 103Define POJO Classes . 104Define Hibernate Mapping File . 106Create Application Class . 107Compilation and Execution . 109Hibernate Annotations. 111Environment Setup for Hibernate Annotation . 111Annotated Class Example . 111@Entity Annotation . 112@Table Annotation . 113TUTORIALS POINTSimply Easy Learning

@Id and @GeneratedValue Annotations. 113@Column Annotation . 113Create Application Class . 113Database Configuration . 115Compilation and Execution . 116Hibernate Query Language . 117FROM Clause . 117AS Clause . 117SELECT Clause . 118WHERE Clause . 118ORDER BY Clause . 118GROUP BY Clause. 118Using Named Paramters . 119UPDATE Clause . 119DELETE Clause . 119INSERT Clause . 119Aggregate Methods . 119Pagination using Query . 120Hibernate Criteria Queries . 121Restrictions with Criteria . 121Pagination using Criteria . 122Sorting the Results . 123Projections & Aggregations . 123Criteria Queries Example . 123Compilation and Execution . 127Hibernate Native SQL . 128Scalar queries . 128Entity queries . 128Named SQL queries. 129Native SQL Example . 129Compilation and Execution . 132Hibernate Caching . 133First-level cache . 133Second-level cache . 134Query-level cache . 134The Second Level Cache . 134Concurrency strategies . 134Cache provider . 135The Query-level Cache . 137TUTORIALS POINTSimply Easy Learning

Hibernate Batch Processing . 138Batch Processing Example . 139Compilation and Execution . 142Hibernate Interceptors. 143How to use Interceptors? . 144Create Interceptors . 144Create POJO Classes . 145Create Database Tables . 145Create Mapping Configuration File . 146Create Application Class . 146Compilation and Execution . 148TUTORIALS POINTSimply Easy Learning

1CHAPTERORM OverviewJDBC stands for Java Database Connectivity and provides a set of Java API for accessing the relationaldatabases from Java program. These Java APIs enables Java programs to execute SQL statements and interactwith any SQL compliant database.JDBC provides a flexible architecture to write a database independent application that can run on differentplatforms and interact with different DBMS without any modification.Pros and Cons of JDBCPros of JDBCCons of JDBC Clean and simple SQL processing Complex if it is used in large projects Good performance with large data Large programming overhead Very good for small applications No encapsulation Simple syntax so easy to learn Hard to implement MVC concept Query is DBMS specificWhy Object Relational Mapping (ORM)?When we work with an object-oriented systems, there's a mismatch between the object model and the relationaldatabase. RDBMSs represent data in a tabular format whereas object-oriented languages, such as Java or C#represent it as an interconnected graph of objects. Consider the following Java Class with proper constructors andassociated public function:public class Employee {private int id;private String first name;private String last name;private int salary;TUTORIALS POINTSimply Easy Learning

public Employee() {}public Employee(String fname, String lname, int salary) {this.first name fname;this.last name lname;this.salary salary;}public int getId() {return id;}public String getFirstName() {return first name;}public String getLastName() {return last name;}public int getSalary() {return salary;}}Consider above objects need to be stored and retrieved into the following RDBMS table:create table EMPLOYEE (id INT NOT NULL auto increment,first name VARCHAR(20) default NULL,last name VARCHAR(20) default NULL,salaryINT default NULL,PRIMARY KEY (id));First problem, what if we need to modify the design of our database after having developed few pages or ourapplication? Second, Loading and storing objects in a relational database exposes us to the following fivemismatch problems.MismatchDescriptionGranularitySometimes you will have an object model which has more classes than thenumber of corresponding tables in the database.InheritanceRDBMSs do not define anything similar to Inheritance which is a natural paradigmin object-oriented programming languages.IdentityA RDBMS defines exactly one notion of 'sameness': the primary key. Java,however, defines both object identity (a b) and object equality (a.equals(b)).AssociationsObject-oriented languages represent associations using object references whereas am RDBMS represents an association as a foreign key column.NavigationThe ways you access objects in Java and in a RDBMS are fundamentally different.The Object-Relational Mapping (ORM) is the solution to handle all the above impedance mismatches.What is ORM?ORM stands for Object-Relational Mapping (ORM) is a programming technique for converting data betweenrelational databases and object oriented programming languages such as Java, C# etc. An ORM system hasfollowing advantages over plain JDBCTUTORIALS POINTSimply Easy Learning

S.N. Advantages1Lets business code access objects rather than DB tables.2Hides details of SQL queries from OO logic.3Based on JDBC 'under the hood'4No need to deal with the database implementation.5Entities based on business concepts rather than database structure.6Transaction management and automatic key generation.7Fast development of application.An ORM solution consists of the following four entities:S.N. Solutions1An API to perform basic CRUD operations on objects of persistent classes.2A language or API to specify queries that refer to classes and properties of classes.3A configurable facility for specifying mapping metadata.4A technique to interact with transactional objects to perform dirty checking, lazy associationfetching, and other optimization functions.Java ORM FrameworksThere are several persistent frameworks and ORM options in Java. A persistent framework is an ORM service thatstores and retrieves objects into a relational database. Enterprise JavaBeans Entity Beans Java Data Objects Castor TopLink Spring DAO Hibernate And many moreTUTORIALS POINTSimply Easy Learning

2CHAPTERHibernate OverviewHibernate is an Object-Relational Mapping(ORM) solution for JAVA and it raised as an open sourcepersistent framework created by Gavin King in 2001. It is a powerful, high performance Object-RelationalPersistence and Query service for any Java Application.Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve thedeveloper from 95% of common data persistence related programming tasks.Hibernate sits between traditional Java objects and database server to handle all the work in persisting thoseobjects based on the appropriate O/R mechanisms and patterns.Hibernate Advantages Hibernate takes care of mapping Java classes to database tables using XML files and without writingany line of code. Provides simple APIs for storing and retrieving Java objects directly to and from the database. If there is change in Database or in any table then the only need to change XML file properties. Abstract away the unfamiliar SQL types and provide us to work around familiar Java Objects. Hibernate does not require an application server to operate. Manipulates Complex associations of objects of your database.TUTORIALS POINTSimply Easy Learning

Minimize database access with smart fetching strategies. Provides Simple querying of data.Supported DatabasesHibernate supports almost all the major RDBMS. Following is list of few of the database engines supported byHibernate. HSQL Database Engine DB2/NT MySQL PostgreSQL FrontBase Oracle Microsoft SQL Server Database Sybase SQL Server Informix Dynamic ServerSupported TechnologiesHibernate supports a variety of other technologies, including the following: XDoclet Spring J2EE Eclipse plug-ins MavenTUTORIALS POINTSimply Easy Learning

3CHAPTERHibernate ArchitectureThe Hibernate architecture is layered to keep you isolated from having to know the underlying APIs.Hibernate makes use of the database and configuration data to provide persistence services (and persistentobjects) to the application.Following is a very high level view of the Hibernate Application Architecture.Following is a detailed view of the Hibernate Application Architecture with few important core classes.TUTORIALS POINTSimply Easy Learning

Hibernate uses various existing Java APIs, like JDBC, Java Transaction API(JTA), and Java Naming andDirectory Interface (JNDI). JDBC provides a rudimentary level of abstraction of functionality common to relationaldatabases, allowing almost any database with a JDBC driver to be supported by Hibernate. JNDI and JTA allowHibernate to be integrated with J2EE application servers.Following section gives brief description of each of the class objects involved in Hibernate ApplicationArchitecture.Configuration ObjectThe Configuration object is the first Hibernate object you create in any Hibernate application and usually createdonly once during application initialization. It represents a configuration or properties file required by the Hibernate.The Configuration object provides two keys components: Database Connection: This is handled through one or more configuration files supported by Hibernate.These files are hibernate.properties and hibernate.cfg.xml.Class Mapping Setup: This component creates the connection between the Java classes and databasetables.SessionFactory ObjectConfiguration object is used to create a SessionFactory object which inturn configures Hibernate for theapplication using the supplied configuration file and allows for a Session object to be instantiated. TheSessionFactory is a thread safe object and used by all the threads of an application.TUTORIALS POINTSimply Easy Learning

The SessionFactory is heavyweight object so usually it is created during application start up and kept for lateruse. You would need one SessionFactory object per database using a separate configuration file. So if you areusing multiple databases then you would have to create multiple SessionFactory objects.Session ObjectA Session is used to get a physical connection with a database. The Session object is lightweight and designed tobe instantiated each time an interaction is needed with the database. Persistent objects are saved and retrievedthrough a Session object.The session objects should not be kept open for a long time because they are not usually thread safe and theyshould be created and destroyed them as needed.Transaction ObjectA Transaction represents a unit of work with the database and most of the RDBMS supports transactionfunctionality. Transactions in Hibernate are handled by an underlying transaction manager and transaction (fromJDBC or JTA).This is an optional object and Hibernate applications may choose not to use this interface, instead managingtransactions in their own application code.Query ObjectQuery objects use SQL or Hibernate Query Language (HQL) string to retrieve data from the database and createobjects. A Query instance is used to bind query parameters, limit the number of results returned by the query, andfinally to execute the query.Criteria ObjectCriteria object are used to create and execute object oriented criteria queries to retrieve objects.TUTORIALS POINTSimply Easy Learning

4CHAPTERHibernate EnvironmentThis chapter will explain how to install Hibernate and other associated packages to prepare a developenvironment for the Hibernate applications. We will work with MySQL database to experiment with Hibernateexamples, so make sure you already have setup for MySQL database. For a more detail on MySQL you cancheck our MySQL Tutorial.Downloading Hibernate:It is assumed that you already have latest version of Java is installed on your machine. Following are the simplesteps to download and install Hibernate on your machine. Make a choice whether you want to install Hibernate on Windows, or Unix and then proceed to the nextstep to download .zip file for windows and .tz file for Unix. Download the latest version of Hibernate from http://www.hibernate.org/downloads. At the time of writing this tutorial I downloaded hibernate-distribution-3.6.4.Final and when you unzipthe downloaded file it will give you directory structure as follows.TUTORIALS POINTSimply Easy Learning

Installing HibernateOnce you downloaded and unzipped the latest version of the Hibernate Installation file, you need to performfollowing two simple steps. Make sure you are setting your CLASSPATH variable properly otherwise you will faceproblem while compiling your application. Now copy all the library files from /lib into your CLASSPATH, and change your classpath variable toinclude all the JARs: Finally copy hibernate3.jar file into your CLASSPATH. This file lies in the root directory of theinstallation and is the primary JAR that Hibernate needs to do its work.Hibernate PrerequisitesFollowing is the list of the packages/libraries required by Hibernate and you should install them before startingwith Hibernate. To install these packages you would have to copy library files from /lib into your CLASSPATH,and change your CLASSPATH variable accordingly.S.N. Packages/Libraries1dom4j - XML parsing ww

All the content and graphics on this tutorial are the property of tutorialspoint.com. Any content from tutorialspoint.com or this tutorial may not be redistributed or reproduced in any way, shape, or form without the written permission of tutorialspoint.com. Failure to do so is a violation of copyright laws.

Related Documents:

Hibernate i About the Tutorial Hibernate is a high-performance Object/Relational persistence and query service, which is licensed under the open source GNU Lesser General Public License (LGPL) and is free to

Suspend (S3) or hibernate (S4) can not be executed if CPU0 is detected offline: Because x86 BIOS requires CPU0 to resume from sleep To successfully resume from suspend/hibernate, CPU0 must be online before suspend or hibernate: Suspend or hibernate

vi CONTENTS 2 Introducing and integrating Hibernate 30 2.1 “Hello World” with Hibernate 31 2.2 Understanding the architecture 36 The core interfaces 38 Callback interfaces 40 Types 40 Extension interfaces 41 2.3 Basic configuration 41 Creating a SessionFactory 42 Configuration in non-managed

Spring Hibernate JSF, Primefaces Intergration (Step by Step) Tool: - IDE: STS 3.3.0.RELEASE (or Eclipse Kepler with Maven and STS plug-in) - Server: Apache Tomcat v7.0 - Database: PostgresQSL 9.1, pgAdmin 1.14.0 Used Technologies: - Spring framework 3.2.3.RELEASE - Hibernate 4.1.0.Final - Myfaces 2.1.12 (

Microsoft name for « suspend to disk » feature Available since Windows 2000. This feature is also implemented in non-MS O.S. (MacOSX, Linux,.) \hiberfil.sys Yes, this is this file! It contains a full dump of the memory How do I hibernate? Start Hibernate Command line: Powercfg /hibernate

Hibernate is an Object-Relational Mapping(ORM) solution for JAVA. It is an open source persistent framework created by Gavin King in 2001. It is a powerful, high performance Object-Relational Persistence and Query service for any Java Application. Hibernate maps Java classes to database tables and from Java data types to SQL data types

Persistence for Idiomatic Java 1 Hibernate Reference Documentation 3.5.6-Final by Gavin King, Christian Bauer, Max Rydahl Andersen, Emmanuel Bernard, and Steve Ebersole and thanks to James Cobb (Graphic Design) and Cheyenne Weaver (Graphic Design)

THE AMERICAN REVOLUTION AND CONFEDERATION, 1774-1787 87 . Thomas Paine, a recent English imntigrant to the colonies, argued strongly for what until then had been considered a radical idea. Entitled Common Sense, Paine's essay argued in clear and forceful language for the colonies becoming independent states and breaking all political ties with the British monarchy. Paine argued that it was .