SlideShare a Scribd company logo
1 of 38
1
What is persistence?
• The storage of an object on a disk or other
permanent storage device or data that exists
from session to session
– as opposed to transient data
• Persistent data typically implies that it is durable
(i.e. will survive a crash or shutdown of the
process) usually with some guarantee of
integrity
• Persistence generally implies use of a database
– One could use the file system (with suitably careful
procedures)
2
3 ways to persist data to the DB
JDBC
http://java.sun.com/products/jdbc/
Spring JDBC
http://www.springframework.org/docs/reference/
Hibernate
http://www.hibernate.org/
3
JDBC Info
• Java Database Connectivity
• Industry standard but has some issues:
– The developer needs to deal with lot of plumbing and
infrastructure, such as endless try-catch-finally-try-catch blocks.
– Applications need complex error handling to ensure that
connections are properly closed after they're used, which makes
the code verbose, bloated, and repetitive.
– JDBC uses the rather uninformative SQLException.
– JDBC has no exception hierarchy
• Bottom Line: Don’t use this!
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
• Hibernate 2-tier web
architecture
• Can send data to
JDBC or XML files
• Best to just use it the
way Sakai does
(JDBC)
• Bottom Line: Use this!
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
• Always turn on hbm2ddl.auto
<prop key="hibernate.hbm2ddl.auto">update</prop>
• You may want to turn this off for production environments
• HSQLDB works well for development and
for demos
– Caveat: You cannot look at the HSQLDB
database without some serious trickery
• If all else fails, switch to HSQLDB file
storage
10
More database tips
• MySQL despite being a “production”
option is actually really easy to set up for
development
– Allows you to look at the database through its
console to see if things are working
– Works well on most platforms and tends to
get into a lock state somewhat easily which
helps you find transaction problems
11
One last database tip
• You can turn on verbose Hibernate
logging to see every SQL statement that it
runs
– Change the following from false to true
<prop key="hibernate.show_sql">false</prop>
• Note: You do NOT want to leave this on in a
production environment
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
• Create a Hibernate SessionFactory
using config settings in your app
– You should only create one Session
Factory per database
• You can create another one when connecting
to an external database
– More info on session configuration:
http://www.hibernate.org/hib_docs/reference/en/html/session-configuration.html
19
Use the Generic Dao package
• The GenericDao is an abstraction layer that
will allow you to use Hibernate with your
persistent objects without needing to write a
DAO at all
• It has usage information in the Javadocs
• Highly configurable and extendable
• Has no Hibernate dependencies in the
interfaces (*any* DAO should be like this)
URL: http://bugs.sakaiproject.org/confluence/display/BOOT/Generic+DAO+package
20
More on GenericDao
• Get the code and javadocs from the VT
Maven repository:
– http://source.edtech.vt.edu/maven/generic-dao/
• Usage (Sakai related) is demonstrated
in the tasklist code here:
– https://source.sakaiproject.org/contrib/programmerscafe/
21
Let’s look at some code!
• Let’s see what it takes to use Hibernate
– Hibernate and Spring packages
– Hibernate mapping file(s)
– Hibernate properties file
– Hibernate related Spring beans
– DAO beans
22
Hibernate and Spring packages
• Download the Hibernate Core from:
http://www.hibernate.org/6.html
– Get at least version 3.1.3
• Download the Spring framework here:
http://www.springframework.org/download
– Get version 1.2.8 for now
– Version 2.0 is risky, wait for patches
23
Hibernate Mapping Files
• Hibernate uses an XML file to map Java
objects onto database columns
• We will create our mapping file from a
simple template attached to the
persistence page
• For applications with many tables, use a
tool to help generate the HBM 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
• Change the class name and table name
– edu.vt.group.toolname.model.MyObject
• Change the id sequence name
• Copy and paste the property block to add the
properties from your persistent object
– owner
– title
– creationDate
• Etc…
26
Creating a DAO for Hibernate
• Create a new class which implements
your DAO interface
– Write a DAO interface if you do not have one
• Extend HibernateDaoSupport
– part of Spring-Hibernate
• Add import for HibernateDaoSupport
– Make sure you use the one for hibernate 3
• Or use Generic DAO package!
27
DAO sample code
public interface MyAppDAO {
}
Make an interface for your DAO
public class MyAppDAOImpl
extends HibernateDaoSupport
implements MyAppDAO {
}
Make an implementation of the DAO interface
Note that it Extends HibernateDaoSupport
28
Spring configuration
• Now we need to tie everything together
with Spring
• First we will tell hibernate about our
MyObject.hbm.xml mapping file
• Next we will give the hibernate stuff to
our DAO implementation
• Finally we will tie the new DAO to the
rest of the webapp
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>
• Setup the connection settings for the
database
30
Create a SessionFactory
(part 1)
<bean id=“myAppSessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref local=“myLocalDataSource" />
</property>
<property name="mappingResources">
<list>
<value>
com/group/myapp/impl/hbm/MyObject.hbm.xml
</value>
</list>
</property>
...
• This ties our persistent objects with the
newly created SessionFactory bean
31
Create a SessionFactory
(part 2)
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.Oracle9Dialect</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.cache.provider_class">
org.hibernate.cache.EhCacheProvider</prop>
<prop key="hibernate.query.substitutions">true 1, false 0</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<!-- create, update, create-drop (wipe and create), or blank -->
</props>
</property>
</bean>
• This sets up the various properties
(could also come from a props file)
32
Create a transaction manager
<bean id=“myAppTransactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref local=“myAppSessionFactory" />
</property>
</bean>
• Creates a spring transaction manager
– We need this in order to manage
transactions in a reasonable way later
– You can manage them manually, but why?
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>
• Create a DAO bean using the data access
object class that we have created
• This injects the SessionFactory into that class
bean
34
Define a declarative
transaction interceptor
• This involves much less work than opening and
closing transactions in code, and is more reliable
– Note that this is what we will access, not the actual DAO
bean (the use of the name of the interface is a convention,
not a requirement)
<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
• Access the persistent objects just like you
would any normal java POJO
• Use the dao operations (save, delete, etc.)
to control the lifetimes of objects
• Take advantage of the Hibernate tools
36
Example App revisit
• Same basic structure
– Alpha is the main class
– Bravo handles user
interaction
– Charlie handles
application logic
– Delta handles data
access
• New implementation of
the Delta interface
– UserString model
class and hbm
Alpha
Charlie
Bravo
Delta
A B = A depends on B
DeltaHibernate
UserString
(hbm and class)
37
Changes to Example App
• Implemented Delta interface using
Spring HibernateDaoSupport
• Adjusted bean definitions to point to the
new implementation
• Created hbm file and model class
• Added bean definitions for Hibernate
Programmers Cafe - Example App Spring Hibernate
38
Any questions?
• Hibernate: http://www.hibernate.org/
• Spring ORM
http://www.springframework.org/docs/reference/orm.html

More Related Content

What's hot

Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Examplekamal kotecha
 
ORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate OverviewORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate OverviewBrett Meyer
 
Java EE 7 Batch processing in the Real World
Java EE 7 Batch processing in the Real WorldJava EE 7 Batch processing in the Real World
Java EE 7 Batch processing in the Real WorldRoberto Cortez
 
Hibernate in XPages
Hibernate in XPagesHibernate in XPages
Hibernate in XPagesToby Samples
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivityVaishali Modi
 
Real World Experience: Integrating DB2 with XPages
Real World Experience: Integrating DB2 with XPagesReal World Experience: Integrating DB2 with XPages
Real World Experience: Integrating DB2 with XPagesSteve_Zavocki
 
Silicon Valley JUG - How to generate customized java 8 code from your database
Silicon Valley JUG - How to generate customized java 8 code from your databaseSilicon Valley JUG - How to generate customized java 8 code from your database
Silicon Valley JUG - How to generate customized java 8 code from your databaseSpeedment, Inc.
 
Hibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance TechniquesHibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance TechniquesBrett Meyer
 
Jdbc Best Practices - DB2/ IDUG - Orlando, May 10, 2004
Jdbc Best Practices - DB2/ IDUG - Orlando, May 10, 2004Jdbc Best Practices - DB2/ IDUG - Orlando, May 10, 2004
Jdbc Best Practices - DB2/ IDUG - Orlando, May 10, 2004derek_clark_ashmore
 
Hibernate jj
Hibernate jjHibernate jj
Hibernate jjJoe Jacob
 
Hibernate - Part 1
Hibernate - Part 1Hibernate - Part 1
Hibernate - Part 1Hitesh-Java
 
Parallel batch processing with spring batch slideshare
Parallel batch processing with spring batch   slideshareParallel batch processing with spring batch   slideshare
Parallel batch processing with spring batch slideshareMorten Andersen-Gott
 
Spring Batch Workshop (advanced)
Spring Batch Workshop (advanced)Spring Batch Workshop (advanced)
Spring Batch Workshop (advanced)lyonjug
 
Advance java session 5
Advance java session 5Advance java session 5
Advance java session 5Smita B Kumar
 
Batching and Java EE (jdk.io)
Batching and Java EE (jdk.io)Batching and Java EE (jdk.io)
Batching and Java EE (jdk.io)Ryan Cuprak
 
Apache Con Us2007 Apachei Batis
Apache Con Us2007 Apachei BatisApache Con Us2007 Apachei Batis
Apache Con Us2007 Apachei Batisday
 

What's hot (19)

Hibernate performance tuning
Hibernate performance tuningHibernate performance tuning
Hibernate performance tuning
 
Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Example
 
ORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate OverviewORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate Overview
 
Java EE 7 Batch processing in the Real World
Java EE 7 Batch processing in the Real WorldJava EE 7 Batch processing in the Real World
Java EE 7 Batch processing in the Real World
 
Hibernate in XPages
Hibernate in XPagesHibernate in XPages
Hibernate in XPages
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
Chap3 3 12
Chap3 3 12Chap3 3 12
Chap3 3 12
 
Real World Experience: Integrating DB2 with XPages
Real World Experience: Integrating DB2 with XPagesReal World Experience: Integrating DB2 with XPages
Real World Experience: Integrating DB2 with XPages
 
Silicon Valley JUG - How to generate customized java 8 code from your database
Silicon Valley JUG - How to generate customized java 8 code from your databaseSilicon Valley JUG - How to generate customized java 8 code from your database
Silicon Valley JUG - How to generate customized java 8 code from your database
 
Hibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance TechniquesHibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance Techniques
 
Jdbc Best Practices - DB2/ IDUG - Orlando, May 10, 2004
Jdbc Best Practices - DB2/ IDUG - Orlando, May 10, 2004Jdbc Best Practices - DB2/ IDUG - Orlando, May 10, 2004
Jdbc Best Practices - DB2/ IDUG - Orlando, May 10, 2004
 
Hibernate jj
Hibernate jjHibernate jj
Hibernate jj
 
Hibernate - Part 1
Hibernate - Part 1Hibernate - Part 1
Hibernate - Part 1
 
Parallel batch processing with spring batch slideshare
Parallel batch processing with spring batch   slideshareParallel batch processing with spring batch   slideshare
Parallel batch processing with spring batch slideshare
 
Spring Batch Workshop (advanced)
Spring Batch Workshop (advanced)Spring Batch Workshop (advanced)
Spring Batch Workshop (advanced)
 
Advance java session 5
Advance java session 5Advance java session 5
Advance java session 5
 
Hpts 2011 flexible_oltp
Hpts 2011 flexible_oltpHpts 2011 flexible_oltp
Hpts 2011 flexible_oltp
 
Batching and Java EE (jdk.io)
Batching and Java EE (jdk.io)Batching and Java EE (jdk.io)
Batching and Java EE (jdk.io)
 
Apache Con Us2007 Apachei Batis
Apache Con Us2007 Apachei BatisApache Con Us2007 Apachei Batis
Apache Con Us2007 Apachei Batis
 

Viewers also liked

Field Service Engineer-LAB
Field Service Engineer-LABField Service Engineer-LAB
Field Service Engineer-LABSreekumar R V
 
Community Events Toolkit
Community Events ToolkitCommunity Events Toolkit
Community Events ToolkitJennifer Graves
 
Fase I Yurelys Rangel C.I V- 10.877.774
Fase I  Yurelys Rangel C.I V- 10.877.774Fase I  Yurelys Rangel C.I V- 10.877.774
Fase I Yurelys Rangel C.I V- 10.877.774Yurelys Rangel
 
fuentes de apoyo económico para la financiación de propuestas o negocios verdes
fuentes de apoyo económico para la financiación de propuestas o negocios verdesfuentes de apoyo económico para la financiación de propuestas o negocios verdes
fuentes de apoyo económico para la financiación de propuestas o negocios verdesVictor Andres Davila Rodriguez
 
Comparative Analysis of Face Recognition Algorithms for Medical Application
Comparative Analysis of Face Recognition Algorithms for Medical ApplicationComparative Analysis of Face Recognition Algorithms for Medical Application
Comparative Analysis of Face Recognition Algorithms for Medical ApplicationAM Publications
 
Secure communication for mobile Adhoc network using (LPIT) Lagrange polynomia...
Secure communication for mobile Adhoc network using (LPIT) Lagrange polynomia...Secure communication for mobile Adhoc network using (LPIT) Lagrange polynomia...
Secure communication for mobile Adhoc network using (LPIT) Lagrange polynomia...AM Publications
 
Analysis of bending strength of bevel gear by FEM
Analysis of bending strength of bevel gear by FEMAnalysis of bending strength of bevel gear by FEM
Analysis of bending strength of bevel gear by FEMAM Publications
 
Comportamento do consumidor - Teorias motivacionais
Comportamento do consumidor - Teorias motivacionaisComportamento do consumidor - Teorias motivacionais
Comportamento do consumidor - Teorias motivacionaisMauricio Valentini
 
E mail маркетинг
E mail маркетингE mail маркетинг
E mail маркетингMedMarketing
 
Training, Pruning and Ratooning in veg.crops
Training, Pruning and Ratooning in veg.cropsTraining, Pruning and Ratooning in veg.crops
Training, Pruning and Ratooning in veg.cropsLav Kumar
 
Recognising Property Rights In One's Body And Its Parts
Recognising Property Rights In One's Body And Its PartsRecognising Property Rights In One's Body And Its Parts
Recognising Property Rights In One's Body And Its PartsBenjamin Cope
 
Plan de Marketing Político
Plan de Marketing PolíticoPlan de Marketing Político
Plan de Marketing PolíticoMariana Circelli
 

Viewers also liked (16)

Field Service Engineer-LAB
Field Service Engineer-LABField Service Engineer-LAB
Field Service Engineer-LAB
 
Valsartan 137862-53-4-api
Valsartan 137862-53-4-apiValsartan 137862-53-4-api
Valsartan 137862-53-4-api
 
Community Events Toolkit
Community Events ToolkitCommunity Events Toolkit
Community Events Toolkit
 
Fase I Yurelys Rangel C.I V- 10.877.774
Fase I  Yurelys Rangel C.I V- 10.877.774Fase I  Yurelys Rangel C.I V- 10.877.774
Fase I Yurelys Rangel C.I V- 10.877.774
 
fuentes de apoyo económico para la financiación de propuestas o negocios verdes
fuentes de apoyo económico para la financiación de propuestas o negocios verdesfuentes de apoyo económico para la financiación de propuestas o negocios verdes
fuentes de apoyo económico para la financiación de propuestas o negocios verdes
 
Quinta sesión curso de Lliurex
Quinta sesión curso de LliurexQuinta sesión curso de Lliurex
Quinta sesión curso de Lliurex
 
Comparative Analysis of Face Recognition Algorithms for Medical Application
Comparative Analysis of Face Recognition Algorithms for Medical ApplicationComparative Analysis of Face Recognition Algorithms for Medical Application
Comparative Analysis of Face Recognition Algorithms for Medical Application
 
Secure communication for mobile Adhoc network using (LPIT) Lagrange polynomia...
Secure communication for mobile Adhoc network using (LPIT) Lagrange polynomia...Secure communication for mobile Adhoc network using (LPIT) Lagrange polynomia...
Secure communication for mobile Adhoc network using (LPIT) Lagrange polynomia...
 
Sila
SilaSila
Sila
 
Dipanjana bhattacharya resume
Dipanjana bhattacharya resumeDipanjana bhattacharya resume
Dipanjana bhattacharya resume
 
Analysis of bending strength of bevel gear by FEM
Analysis of bending strength of bevel gear by FEMAnalysis of bending strength of bevel gear by FEM
Analysis of bending strength of bevel gear by FEM
 
Comportamento do consumidor - Teorias motivacionais
Comportamento do consumidor - Teorias motivacionaisComportamento do consumidor - Teorias motivacionais
Comportamento do consumidor - Teorias motivacionais
 
E mail маркетинг
E mail маркетингE mail маркетинг
E mail маркетинг
 
Training, Pruning and Ratooning in veg.crops
Training, Pruning and Ratooning in veg.cropsTraining, Pruning and Ratooning in veg.crops
Training, Pruning and Ratooning in veg.crops
 
Recognising Property Rights In One's Body And Its Parts
Recognising Property Rights In One's Body And Its PartsRecognising Property Rights In One's Body And Its Parts
Recognising Property Rights In One's Body And Its Parts
 
Plan de Marketing Político
Plan de Marketing PolíticoPlan de Marketing Político
Plan de Marketing Político
 

Similar to Persistence hibernate

Performant Django - Ara Anjargolian
Performant Django - Ara AnjargolianPerformant Django - Ara Anjargolian
Performant Django - Ara AnjargolianHakka Labs
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentationManav Prasad
 
Hadoop and object stores can we do it better
Hadoop and object stores  can we do it betterHadoop and object stores  can we do it better
Hadoop and object stores can we do it bettergvernik
 
Hadoop and object stores: Can we do it better?
Hadoop and object stores: Can we do it better?Hadoop and object stores: Can we do it better?
Hadoop and object stores: Can we do it better?gvernik
 
2010 05-21, object-relational mapping using hibernate v2
2010 05-21, object-relational mapping using hibernate v22010 05-21, object-relational mapping using hibernate v2
2010 05-21, object-relational mapping using hibernate v2alvaro alcocer sotil
 
What is New in Apache Hive 3.0?
What is New in Apache Hive 3.0?What is New in Apache Hive 3.0?
What is New in Apache Hive 3.0?DataWorks Summit
 
Hive 3 New Horizons DataWorks Summit Melbourne February 2019
Hive 3 New Horizons DataWorks Summit Melbourne February 2019Hive 3 New Horizons DataWorks Summit Melbourne February 2019
Hive 3 New Horizons DataWorks Summit Melbourne February 2019alanfgates
 
Hibernate complete Training
Hibernate complete TrainingHibernate complete Training
Hibernate complete Trainingsourabh aggarwal
 
What is new in Apache Hive 3.0?
What is new in Apache Hive 3.0?What is new in Apache Hive 3.0?
What is new in Apache Hive 3.0?DataWorks Summit
 
Orlando DNN Usergroup Pres 12/06/11
Orlando DNN Usergroup Pres 12/06/11Orlando DNN Usergroup Pres 12/06/11
Orlando DNN Usergroup Pres 12/06/11Jess Coburn
 
Pure Speed Drupal 4 Gov talk
Pure Speed Drupal 4 Gov talkPure Speed Drupal 4 Gov talk
Pure Speed Drupal 4 Gov talkBryan Ollendyke
 
Hibernate example1
Hibernate example1Hibernate example1
Hibernate example1myrajendra
 
Drupal upgrades and migrations. BAD Camp 2013 version
Drupal upgrades and migrations. BAD Camp 2013 versionDrupal upgrades and migrations. BAD Camp 2013 version
Drupal upgrades and migrations. BAD Camp 2013 versionDavid Lanier
 

Similar to Persistence hibernate (20)

Performant Django - Ara Anjargolian
Performant Django - Ara AnjargolianPerformant Django - Ara Anjargolian
Performant Django - Ara Anjargolian
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
 
Hadoop and object stores can we do it better
Hadoop and object stores  can we do it betterHadoop and object stores  can we do it better
Hadoop and object stores can we do it better
 
Hadoop and object stores: Can we do it better?
Hadoop and object stores: Can we do it better?Hadoop and object stores: Can we do it better?
Hadoop and object stores: Can we do it better?
 
Scaling PHP apps
Scaling PHP appsScaling PHP apps
Scaling PHP apps
 
Hibernate
HibernateHibernate
Hibernate
 
2010 05-21, object-relational mapping using hibernate v2
2010 05-21, object-relational mapping using hibernate v22010 05-21, object-relational mapping using hibernate v2
2010 05-21, object-relational mapping using hibernate v2
 
Hibernate
HibernateHibernate
Hibernate
 
What is New in Apache Hive 3.0?
What is New in Apache Hive 3.0?What is New in Apache Hive 3.0?
What is New in Apache Hive 3.0?
 
Hive 3 New Horizons DataWorks Summit Melbourne February 2019
Hive 3 New Horizons DataWorks Summit Melbourne February 2019Hive 3 New Horizons DataWorks Summit Melbourne February 2019
Hive 3 New Horizons DataWorks Summit Melbourne February 2019
 
Hibernate in Action
Hibernate in ActionHibernate in Action
Hibernate in Action
 
Hibernate complete Training
Hibernate complete TrainingHibernate complete Training
Hibernate complete Training
 
What is new in Apache Hive 3.0?
What is new in Apache Hive 3.0?What is new in Apache Hive 3.0?
What is new in Apache Hive 3.0?
 
Orlando DNN Usergroup Pres 12/06/11
Orlando DNN Usergroup Pres 12/06/11Orlando DNN Usergroup Pres 12/06/11
Orlando DNN Usergroup Pres 12/06/11
 
Pure Speed Drupal 4 Gov talk
Pure Speed Drupal 4 Gov talkPure Speed Drupal 4 Gov talk
Pure Speed Drupal 4 Gov talk
 
Hybernat and structs, spring classes in mumbai
Hybernat and structs, spring classes in mumbaiHybernat and structs, spring classes in mumbai
Hybernat and structs, spring classes in mumbai
 
Hibernate example1
Hibernate example1Hibernate example1
Hibernate example1
 
Drupal upgrades and migrations. BAD Camp 2013 version
Drupal upgrades and migrations. BAD Camp 2013 versionDrupal upgrades and migrations. BAD Camp 2013 version
Drupal upgrades and migrations. BAD Camp 2013 version
 
Hive at booking
Hive at bookingHive at booking
Hive at booking
 

More from Krishnakanth Goud

More from Krishnakanth Goud (11)

Log4j
Log4jLog4j
Log4j
 
Hibernate java and_oracle
Hibernate java and_oracleHibernate java and_oracle
Hibernate java and_oracle
 
Introduction to Hibernate
Introduction to HibernateIntroduction to Hibernate
Introduction to Hibernate
 
Mule smtp connector
Mule smtp connectorMule smtp connector
Mule smtp connector
 
Fetch records from mysql using mule esb
Fetch records from mysql using mule esbFetch records from mysql using mule esb
Fetch records from mysql using mule esb
 
Running ms sql stored procedures in mule
Running ms sql stored procedures in muleRunning ms sql stored procedures in mule
Running ms sql stored procedures in mule
 
Web service invocation in mule
Web service invocation in muleWeb service invocation in mule
Web service invocation in mule
 
Mule ESB Dropbox connector
Mule ESB Dropbox connectorMule ESB Dropbox connector
Mule ESB Dropbox connector
 
Box connector Mule ESB Integration
Box connector Mule ESB IntegrationBox connector Mule ESB Integration
Box connector Mule ESB Integration
 
Mule esb :Data Weave
Mule esb :Data WeaveMule esb :Data Weave
Mule esb :Data Weave
 
Bluetooth
BluetoothBluetooth
Bluetooth
 

Recently uploaded

Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterMateoGardella
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 

Recently uploaded (20)

Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 

Persistence hibernate

  • 1. 1 What is persistence? • The storage of an object on a disk or other permanent storage device or data that exists from session to session – as opposed to transient data • Persistent data typically implies that it is durable (i.e. will survive a crash or shutdown of the process) usually with some guarantee of integrity • Persistence generally implies use of a database – One could use the file system (with suitably careful procedures)
  • 2. 2 3 ways to persist data to the DB JDBC http://java.sun.com/products/jdbc/ Spring JDBC http://www.springframework.org/docs/reference/ Hibernate http://www.hibernate.org/
  • 3. 3 JDBC Info • Java Database Connectivity • Industry standard but has some issues: – The developer needs to deal with lot of plumbing and infrastructure, such as endless try-catch-finally-try-catch blocks. – Applications need complex error handling to ensure that connections are properly closed after they're used, which makes the code verbose, bloated, and repetitive. – JDBC uses the rather uninformative SQLException. – JDBC has no exception hierarchy • Bottom Line: Don’t use this! From: http://java.sun.com/products/jdbc/
  • 4. 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. 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. 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. 7 Even more Hibernate Info • Hibernate 2-tier web architecture • Can send data to JDBC or XML files • Best to just use it the way Sakai does (JDBC) • Bottom Line: Use this! From: http://www.hibernate.org/354.html
  • 8. 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. 9 Some database tips • Always turn on hbm2ddl.auto <prop key="hibernate.hbm2ddl.auto">update</prop> • You may want to turn this off for production environments • HSQLDB works well for development and for demos – Caveat: You cannot look at the HSQLDB database without some serious trickery • If all else fails, switch to HSQLDB file storage
  • 10. 10 More database tips • MySQL despite being a “production” option is actually really easy to set up for development – Allows you to look at the database through its console to see if things are working – Works well on most platforms and tends to get into a lock state somewhat easily which helps you find transaction problems
  • 11. 11 One last database tip • You can turn on verbose Hibernate logging to see every SQL statement that it runs – Change the following from false to true <prop key="hibernate.show_sql">false</prop> • Note: You do NOT want to leave this on in a production environment
  • 12. 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. 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. 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. 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. 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. 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. 18 Using hibernate in your app • Create a Hibernate SessionFactory using config settings in your app – You should only create one Session Factory per database • You can create another one when connecting to an external database – More info on session configuration: http://www.hibernate.org/hib_docs/reference/en/html/session-configuration.html
  • 19. 19 Use the Generic Dao package • The GenericDao is an abstraction layer that will allow you to use Hibernate with your persistent objects without needing to write a DAO at all • It has usage information in the Javadocs • Highly configurable and extendable • Has no Hibernate dependencies in the interfaces (*any* DAO should be like this) URL: http://bugs.sakaiproject.org/confluence/display/BOOT/Generic+DAO+package
  • 20. 20 More on GenericDao • Get the code and javadocs from the VT Maven repository: – http://source.edtech.vt.edu/maven/generic-dao/ • Usage (Sakai related) is demonstrated in the tasklist code here: – https://source.sakaiproject.org/contrib/programmerscafe/
  • 21. 21 Let’s look at some code! • Let’s see what it takes to use Hibernate – Hibernate and Spring packages – Hibernate mapping file(s) – Hibernate properties file – Hibernate related Spring beans – DAO beans
  • 22. 22 Hibernate and Spring packages • Download the Hibernate Core from: http://www.hibernate.org/6.html – Get at least version 3.1.3 • Download the Spring framework here: http://www.springframework.org/download – Get version 1.2.8 for now – Version 2.0 is risky, wait for patches
  • 23. 23 Hibernate Mapping Files • Hibernate uses an XML file to map Java objects onto database columns • We will create our mapping file from a simple template attached to the persistence page • For applications with many tables, use a tool to help generate the HBM files
  • 24. 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. 25 Template customization • Change the class name and table name – edu.vt.group.toolname.model.MyObject • Change the id sequence name • Copy and paste the property block to add the properties from your persistent object – owner – title – creationDate • Etc…
  • 26. 26 Creating a DAO for Hibernate • Create a new class which implements your DAO interface – Write a DAO interface if you do not have one • Extend HibernateDaoSupport – part of Spring-Hibernate • Add import for HibernateDaoSupport – Make sure you use the one for hibernate 3 • Or use Generic DAO package!
  • 27. 27 DAO sample code public interface MyAppDAO { } Make an interface for your DAO public class MyAppDAOImpl extends HibernateDaoSupport implements MyAppDAO { } Make an implementation of the DAO interface Note that it Extends HibernateDaoSupport
  • 28. 28 Spring configuration • Now we need to tie everything together with Spring • First we will tell hibernate about our MyObject.hbm.xml mapping file • Next we will give the hibernate stuff to our DAO implementation • Finally we will tie the new DAO to the rest of the webapp
  • 29. 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> • Setup the connection settings for the database
  • 30. 30 Create a SessionFactory (part 1) <bean id=“myAppSessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref local=“myLocalDataSource" /> </property> <property name="mappingResources"> <list> <value> com/group/myapp/impl/hbm/MyObject.hbm.xml </value> </list> </property> ... • This ties our persistent objects with the newly created SessionFactory bean
  • 31. 31 Create a SessionFactory (part 2) <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.Oracle9Dialect</prop> <prop key="hibernate.show_sql">false</prop> <prop key="hibernate.cache.provider_class"> org.hibernate.cache.EhCacheProvider</prop> <prop key="hibernate.query.substitutions">true 1, false 0</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <!-- create, update, create-drop (wipe and create), or blank --> </props> </property> </bean> • This sets up the various properties (could also come from a props file)
  • 32. 32 Create a transaction manager <bean id=“myAppTransactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory"> <ref local=“myAppSessionFactory" /> </property> </bean> • Creates a spring transaction manager – We need this in order to manage transactions in a reasonable way later – You can manage them manually, but why?
  • 33. 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> • Create a DAO bean using the data access object class that we have created • This injects the SessionFactory into that class bean
  • 34. 34 Define a declarative transaction interceptor • This involves much less work than opening and closing transactions in code, and is more reliable – Note that this is what we will access, not the actual DAO bean (the use of the name of the interface is a convention, not a requirement) <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. 35 Use Hibernate in code • Access the persistent objects just like you would any normal java POJO • Use the dao operations (save, delete, etc.) to control the lifetimes of objects • Take advantage of the Hibernate tools
  • 36. 36 Example App revisit • Same basic structure – Alpha is the main class – Bravo handles user interaction – Charlie handles application logic – Delta handles data access • New implementation of the Delta interface – UserString model class and hbm Alpha Charlie Bravo Delta A B = A depends on B DeltaHibernate UserString (hbm and class)
  • 37. 37 Changes to Example App • Implemented Delta interface using Spring HibernateDaoSupport • Adjusted bean definitions to point to the new implementation • Created hbm file and model class • Added bean definitions for Hibernate Programmers Cafe - Example App Spring Hibernate
  • 38. 38 Any questions? • Hibernate: http://www.hibernate.org/ • Spring ORM http://www.springframework.org/docs/reference/orm.html