Professional Documents
Culture Documents
Object-Relational Mapping and Hibernate
Object-Relational Mapping and Hibernate
and
Hibernate
Problem area
• When working with object-oriented systems, there’s a
mismatch between the object model and the relational
database
• How do we map one to the other?
Degree
• Why object-oriented models?
– Business logic can be implemented in
Java (opposed to stored procedures)
– Allows for use of design patterns and
concepts like polymorphism
– Improves
I code
d reuse and d maintainability
i t i bilit
Magic happens
Degree
here!
ORM / Hibernate
(Database)
Example app: The EventManager
Java Hibernate
objects API
Hibernate
Hibernate
configuration
mapping files
file
Java objects
public class Event
{
Identifier property private int id;
private String title;
private Date date;
private Set<Person> persons = new HashSet<Person>();
Java Hibernate
objects API
Hibernate
Hibernate
configuration
mapping files
file
Hibernate mapping files
• Tells Hibernate which tables and columns to use to load
and store objects
<!DOCTYPE
!DOCTYPE hibernate
hibernate-mapping
mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
DTD "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
Cl
Class element
l t <class name=”no
name= no.uio.inf5750.Event
uio inf5750 Event” table=
table=”events”>
events >
<set name=”persons”
p table=”event_p
persons”>
<key column=”event_id”/>
Unidirectional many-to-many <many-to-many column=”person_id”
association mapping class=”no.uio.inf5750.example.model.Person”/>
</set>
</class>
Filename: Event.hbm.xml </hibernate-mapping>
Property mapping
The name property refers Title must be
to the get/set-methods not null and unique
...
<property name=”title” not-null=”true” unique=”true”/>
<
<property
t name=”date”
”d t ” type=”Date”
t ”D t ” column=”event_date”/>
l ” t d t ”/>
...
<many-to-many column=”person_id”
Column
C l name class=”no
class= no.uio.inf5750.example.model.Person
uio inf5750 example model Person”/>
/>
for ”other” side
of association </set>
...
Reference to the
associated class
Hibernate mapping types
• Hibernate will
Hib ill translate
l JJava types to SQL / d
database
b types
for the properties of your mapped classes
Java Hibernate
objects API
Hibernate
Hibernate
configuration
mapping files
file
The Hibernate configuration file
<!DOCTYPE hibernate-configuration PUBLIC
DTD "-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
hibernate configuration
<session-factory>
JDBC connection
configuration <property name="hibernate.connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="hibernate
name= hibernate.connection.url
connection url">jdbc:hsqldb:hsql://localhost</property>
>jdbc:hsqldb:hsql://localhost</property>
<property name="hibernate.connection.username">sa</property>
Specifies the SQL <property name="hibernate.connection.password"></property>
variant to generate
<property name="dialect">org.hibernate.dialect.HSQLDialect</property>
<property name="hibernate.hbm2ddl.auto">create-drop</property>
Automatic generation
of database schema <mapping resource=”Event.hbm.xml"/>
<mapping resource=”Person.hbm.xml”/>
Mapping files </session-factory>
Filename: </hibernate-configuration>
hibernate.cfg.xml
Example app: The EventManager
Java Hibernate
objects API
Hibernate
Hibernate
configuration
mapping files
file
The Configuration class
• Represents a set of
mapping files Configuration configuration = new Configuration()
.addResource( ”Event.hbm.xml” )
• Mapping
M i fil
files can b
be specified
ifi d .addResource(
ddR ( ”P
”Person.hbm.xml”
hb l” ));
programmatically or through
the Hibernate configuration file ...or...
• Intended as a startup-time
object
objec Configuration configuration = new Configuration();
configuration.configure();
Loads Hibernate.cfg.xml
from the classpath
The SessionFactory interface
• Obtained from a Configuration
instance SessionFactory sessionFactory =
configuration.buildSessionFactory();
• Shared
Sh d among application
li ti
threads
• Main purpose is to provide
Session instances
• Allowed to instantiate more
than one SessionFactory
• Sophisticated implementation
of the factory design pattern
The Session interface
• Obtained from a
SessionFactory instance Session session =
sessionFactory.openSession();
• Main
M i runtime
ti interface
i t f b
between
t
a Java application and Hibernate
• Responsible for storing and
retrieving objects
• Think of it as a collection of loaded
objects related to a single unit of work
Instance states
• An object instance state is related to the persistence
context
• The
Th persistence
i t context
t t = a Hibernate
Hib t SSession
i instance
i t
• Three types of instance states:
– Transient
• The instance is not associated with any persistence context
– Persistent
• The instance is associated with a persistence context
– Detached
• Th
The instance
i t was associated
i t d with
ith a persistence
i t context
t t which
hi h h
has
been closed – currently not associated
The Session interface
Make a transient object Event event = new Event( ”title”, new Date() );
persistent
I t
Integer id = (Integer)
(I t ) session.save(
i ( eventt );
)
Load an object – if
Event event = (Event) session
session.load(
load( Event
Event.class,
class id );
matching row exists
Load an object – if
Event event = (Event) session.get( Event.class, id );
unsure about matching row
(SUCCESS)
Transaction commit
Transactions
• Most common pattern Session session = sessionFactory.openSession();
(REQUEST) try
{
transaction = session.beginTransaction();
Retrieve a Hibernate Session
session.save( event );
session.save( person );
Begin new transaction transaction.commit();
}
catch ( RuntimeException ex )
{
Execute database operations
if ( transaction != null )
{
transaction.rollback();
throw ex;
Commit transaction
}
}
finally
{
Flush and close Session
session.close();
}
(RESPONSE)
Example: The EventManager
Java Hibernate
objects API
Hibernate
Hibernate
configuration
mapping files
file
Advantages of ORM
• Productivity
– Eliminates lots of repetitive code – focus on business logic
– Database schema is generated automatically
• Maintainability
– Fewer lines of code – easier to understand
– Easier to manage change in the object model
Advantages of ORM
• Performance
– Lazy loading – associations are fetched when needed
– Caching
• Database vendor independence
– The underlying database is abstracted away
– Can be configured outside the application
Resources
• Books on Hibernate
– Christian Bauer and Gavin King: Hibernate in Action
– James Elliot: Hibernate – A Developer
Developer’ss notebook
– Justin Gehtland, Bruce A. Tate: Better, Faster, Lighter Java