This tutorial shows a simple example using Hibernate. We will create a simple Java application, showing how Hibernate works. Consulting / Development I am a freelancer and can be booked for your projects. In cooperation with otherspecialists, you have even access to a development team of highly qua lified experts. Java Persistence and Hibernate Training I offer training on Hibernate and Java Persistence (G lassfish with Oracle Toplinkor JBoss). General Author: Sebastian HennebruederDate: First edition 2005 updated February, 9th 2008 Used software and frameworks Eclipse 3.x MyEclipse or alternatively Hibernate Tools are recommended but optional Hibernate 3.x (I used 3.3) Source code: http://www.laliluna.de/download/first-hibernate-example- tutorial.zip The sources does not include the libraries. Download the libraries from hibernate.org and your dat abase driver and add them to t he project as explained below! The example must be configured to work with your database sett in gs! Read the t utori al. PDF version of the tutorial: http://www.laliluna.de/download/first-hibernate- example-tutorial-en.pdf Java Persistence and Hibernate Training I offertraining on Hibernate and Java Persistence (Glassfish with Oracle Toplink orJBoss). Get more informatio n.Consulting / Developme nt I am a freelancerand can be booked foryourprojects. In cooperatio n with otherspecialists, you have even access to a developme nt team ofhighly qualified experts. Get more informatio n.Hibernate and Java Persistence
23
Embed
This Tutorial Shows a Simple Example Using Hibernate
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
8/8/2019 This Tutorial Shows a Simple Example Using Hibernate
The sources does not include the libraries. Download the libraries from
hibernate.org and your database driver and add them to the project as explained below! The example must be configured to work with your database settings!
Read the tutorial.
PDF version of the tutorial: http://www.laliluna.de/download/first-hibernate-
example-tutorial-en.pdf
Java
Persistenceand
HibernateTraining
I offer training on
Hibernateand Java
Persistence(Glassfish
withOracle
Toplink or JBoss).
Get more
information.
Consulting/
Development
I am afreelancer
and can be booked for
your
projects. Incooperation with
other specialists,
you haveeven
access to adevelopme
nt team of highly
qualifiedexperts.
Get moreinformatio
n.
Hibernate
and JavaPersistence
8/8/2019 This Tutorial Shows a Simple Example Using Hibernate
Old PDF version with Hibernate 2: http://www.laliluna.de/download/first-
hibernate-2-example-tutorial-en.pdf
Short introductionHibernate is a solution for object relational mapping and a persistencemanagement solution or persistent layer. This is probably not understandable for
anybody learning Hibernate.
What you can imagine is probably that you have your application with some
functions (business logic) and you want to save data in a database. When you useJava all the business logic normally works with objects of different class types.
Your database tables are not at all objects.
Hibernate provides a solution to map database tables to a class. It copies one row
of the database data to a class. In the other direction it supports to save objects to
the database. In this process the object is transformed to one or more tables.
Developer
Guide
XML andAnnotation
s,Performan
ce chapter,Hibernate
search,Integration
withSpring,
EJB3 andJSF
Availableas up to
date ebook Get moreinformatio
n.
News
Devoxx2009
Presentation
(Nov. 18, 2009)
Window IdBrowser
Extension(Blog)
(Nov. 13, 2
009)JSF 2evaluationand test
(Blog) (Nov. 10, 2
009)
Devoxx
8/8/2019 This Tutorial Shows a Simple Example Using Hibernate
Saving data to a storage is called persistence. And the copying of tables to objects
and vice versa is called object relational mapping.
Create a Java ProjectUsing Eclipse press the keys Ctrl+n (Strg+n) to create a new project. Select a Java project. We will call it FirstHibernateExample.
Prepare the project for Hibernate
using MyEclipse
When you are using MyEclipse, right click on your project in the package explorer
andchoos
e Add Hiber
natecapa
bilitie s.
presentation on
ChoosingWeb
Framework
s (Blog) (Sep. 17, 2009)
JQueryJSON
autocomplete library
(Blog) (Sep. 01, 2
009)
Better Java
application packaging
- JSR 277Java
ModuleSystem
(Blog) (Aug. 21, 2
009)
Performance Tuning
Tips for Hibernate
and JavaPersistence
(Jan. 27, 2009)
Hibernate /Java
PersistenceeBook
update
(Jan. 27, 2009)
Hibernate
Searchwith
Lucene (Jan. 12, 2
009)
8/8/2019 This Tutorial Shows a Simple Example Using Hibernate
Continue the wizard and create a new hibernate.cfg.xml in the src directory.
In the last step you can create a Hibernate SessionFactory. I prefer to create my
own. You can find it below.
Prepare the project for Hibernate for
anybody
If you do not use MyEclipse, you can use the ant build to retrieve the libs using
Ivy or alternatively just download Hibernate from the websitehttp://www.hibernate.org/
You will need at least Hibernate Core. If you want to use Annotations you needHibernate Annotations and if you want to use Hibernate Search, you need to
download Hibernate Search as well.
Extract the file. Hibernate comes with a long list of libraries. You do not need allof them. There is a REAME file in the lib directory explaining what is required.
Open your project properties, select ³Java Build Path´, click on ³Add ExternalJars´ and add the libaries shown below to your project path.
The following list includes the libraries to use Hibernate with XML or annotations,EHCache, PostgreSQL and logging over log4j.
y antlr.jar
y backport-util-concurrent.jar y hibernate-commons-annotations.jar
y hibernate-annotations.jar y postgresql.jar
y hibernate-ehcache.jar y log4j.jar
y ejb3-persistence.jar y slf4j-log4j12.jar
y slf4j-api.jar
y javassist.jar y commons-collections.jar y dom4j.jar
y lucene-core.jar y commons-logging.jar
y hibernate-search.jar y jta.jar
y hibernate-core.jar
Notes fromthe
DevoxxConference
(Dec. 16, 2
008)
8/8/2019 This Tutorial Shows a Simple Example Using Hibernate
/*** @author hennebrueder This class garanties that only one single
SessionFactory* is instanciated and that the configuration is donethread safe as* singleton. Actually it only wraps the HibernateSessionFactory.* You are free to use any kind of JTA or ThreadtransactionFactories.*/public class SessionFactoryUtil {
/** The single instance of hibernate SessionFactory */private static org.hibernate.SessionFactory sessionFactory;
/**
* disable contructor to guaranty a single instance*/
log4j:WARN No appenders could be found for logger (TestClient).log4j:WARN Please initialize the log4j system properly.
Create a file named log4j.properties in the root directory and insert the following:
### direct log messages to stdout ###log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target=System.outlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p%c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to'debug' ###
### enable the following line if you want to track down connection###### leakages when using DriverManagerConnectionProvider ####log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace
Add the database driver
8/8/2019 This Tutorial Shows a Simple Example Using Hibernate
Even Hibernate needs a database driver to access a database. Open the project properties, click on ³Java Build Path´, select ³Add External Jars´ and add your
database driver. If you use PostgreSQL you can find your database driver onhttp://jdbc.postgresql.org if you use MySQL have a look here
http://www.mysql.de/products/connector/j
Create database and tables.
Create a database with MySql or PostgreSQL or anything you like. Call it³firsthibernate´.
Using PostgreSql use the following script to create your table:
CREATE TABLE "public"."honey" (id SERIAL,name text,taste text,PRIMARY KEY(id)
Create a new class named ³Honey´ in the package ³de.laliluna.example´. Add
three fields id, name and taste and generate (Context menu -> Source -> GenerateGetter and Setter) or type the getters and setters for the fields. Then create an
empty constructor.
package de.laliluna.example;
public class Honey {private Integer id;private String name;private String taste;
public Honey(){
}
8/8/2019 This Tutorial Shows a Simple Example Using Hibernate
This tutorial is copyright of Sebastian Hennebrueder, laliluna.de. You maydownload a tutorial for your own personal use but not redistribute it. You must not
remove or modify this copyright notice.
The tutorial is provided as is. I do not give any warranty or guaranty any fitness
for a particular purpose. In no event shall I be liable to any party for direct,indirect, special, incidental, or consequential damages, including lost profits,arising out of the use of this tutorial, even if I has been advised of the possibility of
such damage.
Copyright (c) 2004-2009 by Sebastian Hennebrueder, laliluna.de Impressum