Home >> Hibernate
Setting up of Environment for Examples we shall be exploring
in following articles/writings of using Hibernate related mapping
of POJO/domain objects with database tables/views
I have used following Software Environment for compilation and
running these examples:
IDE (Integrated Development Environment)- Eclipse version 3.2 -
Java Platform version "1.6.0_17" -
Hibernate version 3.2 -
HSQLDB version 1.8.0 -
Once all these software environment is set in the Development Environment.
Then comes the time to create appropriate Eclipse example workspace and by creating
all the folder structures and files, including Java, XML mapping and Database objects,
along with SQL statements in a text file.
Create a Eclipse workspace at Eclipse startup time dialog box or by navigating
to "File->Switch Workspace" menu item.
Create a Java Project by navigating to the "File->New->Project" menu item
Choose "Java->Java Project" dialogbox dropdown selection
Fill in relevant details including the name of the Java Project at your
convenience and as per your local development Java Environment
After creating of the Java Project, create src (as source folder) and lib
(for JAR files) folders.
Right click the project and go to Project Properties and a dialog box appears.
Navigate to "Java Build Path" in the left section. And select Source tab in the
right section.
Just make sure your source src folder is shown in the "source folders on build path"
and bin as default output folder (below default output folder)
Following set of JAR files I have used locally in my Local Dev environment
to make these example run smoothly without any design/compile time or
runtime exceptions.
antlr-2.7.6.jar
asm.jar
asm-attrs.jar
cglib-2.1.3.jar
commons-collections-2.1.1.jar
commons-logging-1.0.4.jar
dom4j-1.6.1.jar
hibernate3.jar
hsqldb.jar
jta.jar
log4j-1.2.11.jar
|
Right click the project and navigate to project properties.
Go to Java Build Path section in left, and then select Libraries Tab
Click Add Jars and select all the JAR files shown under Project_Name/lib folder.
Apply/OK these changes to the Java Project.
I think, above steps are essential steps to setup workspace for further
development proceedings as per this examples of using Hibernate to follow:
Example case study:
In an amusement park, there are many rides, and each ride could have certain capacity,
and price associated with it. All visitors are supposed to fill-in self details such
as name, age (why age! because certain rides are not meant for children below 18 years of age).
Design of this example using a very abstract Class Relationship Collaboration format:
Major components are
AmusementPark - many rides
Ride - capacity
Visitor - Name, age
Capacity - number of seats
One Visitor can choose to go for/ enjoy many Rides.
So we can have domain POJOs are:
AmusementPark
name of type String
rides of type Collection of Ride
Ride
name of type String
capacity of type Capacity
visitors of type Collection of visitor
Capacity
size of type int
Visitor
name of type String
age of type int.
|
Hibernate mappings :
1. AmusementPark and Ride share one to many mapping
2. Ride and Capacity share one to one mapping
3. Ride and AmusementPark share many to one mapping
4. Ride and Visitor share one to many mapping.
|
Hibernate mapping files as follows:
AmusementPark-Ride.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
/**
* This code is provide on "AS IS" basis.
* Copyright: Guddu
* Source: http://www.techienjoy.com
*/
-->
<hibernate-mapping package="com.example">
<class name="Amusement" table="Amusement_Park">
<id name="name" access="property" column="ap_name"/>
<bag name="rides" cascade="persist">
<key column="rides"/>
<one-to-many class="Ride"/>
</bag>
</class>
<class name="Ride" table="Ride_Info">
<id name="name" access="property" column="ride_name"/>
</class>
</hibernate-mapping>
|
This is the very simplest form of mapping between Amusement and Ride
domain classes:
Amusement.java
/**
* This code is provide on "AS IS" basis.
* Copyright: Guddu
* Source: http://www.techienjoy.com
*/
package com.example;
import java.util.Collection;
public class Amusement {
private String name;
private Collection rides;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Collection getRides() {
return rides;
}
public void setRides(Collection rides) {
this.rides = rides;
}
}
|
and
Ride.java
/**
* This code is provide on "AS IS" basis.
* Copyright: Guddu
* Source: http://www.techienjoy.com
*/
package com.example;
import java.util.Collection;
public class Ride {
private String name;
private Capacity capacity;
private Collection visitors;
public Capacity getCapacity() {
return capacity;
}
public void setCapacity(Capacity capacity) {
this.capacity = capacity;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Collection getVisitors() {
return visitors;
}
public void setVisitors(Collection visitors) {
this.visitors = visitors;
}
}
|
In order to check whether the mapping defined in the HBM mapping
XML file (as shown above) is correct without any mistakes,
as I have written this file based on my own understanding of related
Hibernate Mapping tags such as "bag", "one-to-many" etc.
I choose to write a simple test client and test this mapping.
But before doing any unit testing, I had to write a configuration
XML file for creating SessionFactory using HSQLD as persistence.
So following is the hibernate.cfg.xml file:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<!--
/**
* This code is provide on "AS IS" basis.
* Copyright: Guddu
* Source: http://www.techienjoy.com
*/
-->
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">
org.hsqldb.jdbcDriver
</property>
<property name="connection.url">
jdbc:hsqldb:hsql://localhost/
</property>
<property name="connection.username">sa</property>
<property name="connection.password"></property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">
org.hibernate.dialect.HSQLDialect
</property>
<!-- Enable Hibernate's automatic session context management
<property name="current_session_context_class">
thread
</property> -->
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<mapping resource="AmusementPark-Ride.hbm.xml"/>
</session-factory>
</hibernate-configuration>
|
As you might have noted from the above configuration for SessionFactory
I choose to create all tables in database at runtime only.
This is just to speed up testing these mapping, instead of creating all
the Table script manually.
Now my test client/harness tends to be very simple and straight forward
as to only create a Hibernate SessionFactory, then Open a Hibernate
Session for persist operation to create a Amusement and Ride records
at one time, as the cascade="persist" is present in the bag element of
Amusement related mapping.
Client.java
/**
* This code is provide on "AS IS" basis.
* Copyright: Guddu
* Source: http://www.techienjoy.com
*/
import java.util.Collection;
import java.util.HashSet;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.apache.log4j.Logger;
import com.example.Amusement;
import com.example.Ride;
public class Client {
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from hibernate.cfg.xml
sessionFactory = new Configuration()
.configure().buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void createRecord()
{
System.out.println(getSessionFactory());
Session session = getSessionFactory().openSession();
Transaction trx = session.beginTransaction();
trx.begin();
Amusement ams = new Amusement();
ams.setName("IQTF Park");
Ride ride1 = new Ride();
ride1.setName("Round Fun");
Collection colRides = new HashSet();
colRides.add(ride1);
ams.setRides(colRides);
session.persist(ams);
trx.commit();
session.close();
}
/**
* @param args
*/
public static void main(String[] args) {
createRecord();
}
}
|
After running this Client, is it seen that appropriate tables are
created in database, like Amusement_Park and Ride_Info with appropriate
records as follows:
Amusement_Park
AP_NAME
IQTF Park
| |
Ride_Info
Ride_Name | Rides
Round Fun | IQTF Park
|
If anything missed out , please let me know at
techienjoy at yahoo . com