Persistence Hibernate
Persistence Hibernate
Persistence Hibernate
and
Intro to Hibernate
Aaron Zeckoski
azeckoski@gmail.com
2
3 ways to persist data to the DB
JDBC
http://java.sun.com/products/jdbc/
Spring JDBC
http://www.springframework.org/docs/refere
nce/jdbc.html
Hibernate
http://www.hibernate.org/
3
JDBC Info
From: http://java.sun.com/products/jdbc/ 4
Spring JDBC Info
• Abstraction framework for JDBC
– i.e. It does lots of stuff for you!
• Some features of Spring JDBC
– JdbcDaoSupport – superclass, provides JdbcTemplate access
– Spring provides an abstract exception layer, moving verbose
and error-prone exception handling out of application code into
the framework. The framework takes care of all exception
handling; application code can concentrate on using appropriate
SQL.
– Spring provides a significant exception hierarchy for your
application code to work with in place of SQLException.
– For creating instances of oracle.sql.BLOB (binary large object)
and oracle.sql.CLOB(character large object), Spring provides the
class org.springframework.jdbc.support.lob.OracleLobHandler.
• Bottom Line: If you love writing SQL, use this!
From: http://www.springframework.org/docs/reference/jdbc.html 5
Hibernate Info
• Object / Relational mapping (ORM) and persistence /
query framework
– i.e. It does even more stuff for you!
• Some features of Hibernate
– HibernateDaoSupport – superclass, easy HibernateTemplate access
– Database independence - sits between the database and your java code, easy
database switch without changing any code
– Object / Relational Mapping (ORM) - Allows a developer to treat a database like
a collection of Java objects
– Object oriented query language (HQL) - *Portable* query language, supports
polymorphic queries etc.
– You can also still issue native SQL, and also queries by “Criteria” (specified
using “parse tree” of Java objects)
– Hibernate Mapping - Uses HBM XML files to map value objects (POJOs) to
database tables
– Transparent persistence - Allows easy saves/delete/retrieve for simple value
objects
– Very high performance “in general” due to intelligent (2-level) caching, although
in a few cases hand-written SQL might beat it
From: http://www.hibernate.org/ 6
More Hibernate Info
• Hibernate basically
sits between the DB
and your code
• Can map persistent
objects to tables
• In Sakai, the
Hibernate
configuration is set
for you already
From: http://www.hibernate.org/hib_docs/v3/reference/en/html/architecture.html 7
Even more Hibernate Info
From: http://www.hibernate.org/354.html 8
Hibernate Commentary
• Beyond the hype:
– Hibernate *is* the best ORM persistence framework
• probably in any language
– Not to say it is without numerous issues
• ORM is a tricky problem and general solutions are very difficult
– Many aspects of the Hibernate framework are “over-eager”
• lazy Collections, cascade options, long transactions
– Many aspects of Hibernate are overly rigid
• proxy behaviour, initial configuration sets cannot be changed, poor
cross-ClassLoader behaviour
• Advice
– Use it cautiously! (pay attention to tips)
– Avoid lazy Collections, be conservative with cascade options
– In general just use it on one entity at a time, with explicit
save/load on for each database operation
– In some cases you may still actually want to fall back to SQL
• recommended by the Hibernate team for certain situations
9
Some database tips
11
One last database tip
12
Hibernate Development
• 4 methods of development using Hibernate
• Top down (good for existing code)
– implement a Java (JavaBeans) object model
– write a mapping document by hand, or generate it from XDoclet tags
– export the database tables using the Hibernate Tools
• Bottom up (good for existing database or code conversion)
– start with an existing data model
– use the Hibernate Tools to generate the mapping documents
– use the Hibernate Tools to generate skeletal Java code
– fill in the business logic by hand
• Middle out (good for new development)
– express your conceptual object model directly as a mapping document
– use the Hibernate Tools to generate skeletal Java code
– fill in the business logic by hand
– export the database tables using the Hibernate Tools
• Meet in the middle (good for existing JDBC to Hibernate switch)
– start with an existing data model and existing Java classes
– write a mapping document to adapt between the two models
From: http://www.hibernate.org/355.html 13
Hibernate Tips -
Avoid primitives
• Don’t use primitives for properties on
persistent objects
– This works fine in general but it does not
work if you are doing a findByExample
• If you do decide to use primitives, you cannot
leave them null/unset when doing a
findByExample or they will be set to the default
value for that primitive
– Things seem to work better when not using
primitives sometimes (e.g. Boolean)
14
Hibernate Tips -
don’t preset values
• Don’t set the values of persistent
objects in the POJO
– This can cause problems with frameworks
that expect to be able to instantiate the
POJO with all properties unset
– It may be more work to set the properties
for all non-null attributes but it is worth it
15
Hibernate Tips -
save dependent objects first
• If you have any dependent entities as
properties of a persistent object you
*must* save them before saving the
parent class
– Hibernate has numerous “cascade” options
that claim to do this automatically, but it is
best to start simple
– The same thing goes for deleting
16
Hibernate Tips -
non-primitive generated ids
• Use non-primitive generated ids for the
primary key of persistent objects
– It is more efficient and is a good idea in
most databases anyway
– Use java.lang.Long or java.lang.String for
best results
• More best practices here:
http://www.hibernate.org/hib_docs/reference/en/html/best-practices.html
17
Hibernate Tools
• Hibernate provides a set of Eclipse tools
http://www.hibernate.org/255.html
– Mapping Editor: An editor for Hibernate XML mapping files,
supporting auto-completion and syntax highlighting
– Console: a view in Eclipse. Provides a tree overview of console
configurations and interactive view of persistent classes and
relationships. Also allows the execution of HQL queries against
your database and browsing of results in Eclipse.
– Development Wizards: Includes the Hibernate configuration
(cfg.xml) files wizard and reverse engineering wizard for turning
an existing database schema into POJO source files and HBM
files.
From: http://www.hibernate.org/255.html 18
Using hibernate in your app
19
Use the Generic Dao package
URL: http://bugs.sakaiproject.org/confluence/display/BOOT/Generic+DAO+package 20
More on GenericDao
21
Let’s look at some code!
22
Hibernate and Spring packages
23
Hibernate Mapping Files
24
Basic HBM template
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="org.sakaiproject.toolname.model.MyObject "
table="TOOLNAME_MYOBJECT">
<id name="id" type="long">
<generator class="native">
<param name="sequence">MYOBJECT_ID_SEQ</param>
</generator>
</id>
<property name="myProperty" type="string"
length="255" not-null="true”/>
</class>
</hibernate-mapping>
25
Template customization
26
Creating a DAO for Hibernate
27
DAO sample code
Make an interface for your DAO
public interface MyAppDAO {
}
28
Spring configuration
29
Create a Data Source
<bean id=“myLocalDataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>oracle.jdbc.driver.OracleDriver</value>
</property>
<property name="url">
<value>jdbc:oracle:thin:@myDB.host.com:1521:SCHEMA</value>
</property>
<property name="username">
<value>USERNAME</value>
</property>
<property name="password">
<value>PASSWORD</value>
</property>
</bean>
33
Create a DAO bean
<bean id=“com.group.myapp.dao.target.MyAppDAO"
class=“com.group.myapp.dao.impl.MyAppDAOImpl"
init-method="init">
<property name="sessionFactory">
<ref local=“myAppSessionFactory" />
</property>
</bean>
34
Define a declarative
transaction interceptor
<bean id=“com.group.myapp.dao.MyAppDAO"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="target">
<ref local=“com.group.myapp.dao.target.MyAppDAO"/>
</property>
<property name="transactionManager">
<ref bean=“myAppTransactionManager" />
</property>
<property name="transactionAttributes">
<props>
<prop key="*">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>
35
Use Hibernate in code
36
Example App revisit
• Same basic structure Alpha
– Alpha is the main class
– Bravo handles user
Bravo
interaction
– Charlie handles
application logic Charlie
UserString
– Delta handles data (hbm and class)
access
• New implementation of
DeltaHibernate Delta
the Delta interface
– UserString model
class and hbm A B = A depends on B
37
Changes to Example App
38
Any questions?
• Hibernate: http://www.hibernate.org/
• Spring ORM
http://www.springframework.org/docs/reference/orm.html
39