Gopal Patel
Hibernate – Object Relation Mapper
Purpose »To
learn about hibernate persistence framework and its architecture »To learn how hibernate is configured and what are the components required in an application using hibernate »To understand various associations & how to map them. »To learn what are the types of objects and how to work with them »To learn inheritance and component mapping »To master HQL and other fetching strategies »To understand how to modify data »An overview of cache management, transaction management and other advanced features
1
Introduction to different ways of persisting data
Without Databases
Object Serialization
Uses the file system for storing the serialized object forms. Not a object relation mapping technique. Only accessible through java language. Bad choice for storing enterprise data.
With Databases (RDBMS )
JDBC
Entity Beans (BMP and CMP)
EJB require a one-to-one mapping to database tables Requires application server supporting EJB Container
JDO
Simply provide API accessing database, No object relation mapping technique Database dependent code
Commercial from individual vendors. Mappings not standard
O/R Mapping tool like Hibernate
Rich features with total abstraction to databases. Provides resolutions to majority concerns on OR mapping.
2
ORM
Object relation mapping fundamentals Objects to integrate into Relational model Object modeling describes system through objects, Association, behavior, state, inheritance Relational modeling describes system through information. Relation, Attribute, Domain Object-relational mapping is the process of transforming between object and relational modeling approaches
4
Object relation mapping Advantages Natural programming model Reduced Line Of Code Code can be run / Tested out side the container Classes may be reused in non persistence context Minimum database access with smart fetching strategies Opportunities for aggressive caching Structural mapping more robust when Object/Relational data model changes.
5
Introduction to Hibernate
Why Hibernate ? »Open
source »13000 downloads / month »Powerful queries »Support for detached persistent objects »Extensive RDBMS support »Tools support »Persistence for java beans or POJO
7
RDBMS Support Hibernate is tested with wide range of databases.
DB2 7.1, 7.2; MySQL 3.23; PostgreSQL 7.1.2, 7.2, 7.3; Oracle 8i, 9i; Sybase 12.5 (JConnect 5.5); Interbase 6.0.1 (Open Source) With Firebird InterClient 2.01; HypersonicSQL 1.61, 1.7.0; Microsoft SQL Server 2000; Mckoi SQL 0.93 Progress 9 Pointbase Embedded 4.3 SAP DB 7.3
8
Tools Support XDoclet
Modeling tools / Code generator
Middlegen AndroMDA IDE Plug-in support: Eclipse, IDEA
9
Hibernate application components Hibernate Libraries » Hibernate configuration file » Hibernate mapping files (HBM files) » POJO classes » Main class »
10
Hibernate Environment antlr.jar cglib.jar asm.jar asm-attrs.jars commons-collections.jar commons-logging.jar hibernate3.jar jta.jar dom4j.jar log4j.jar
11
First trip to Hibernate World Employee Java Object
“Employee” DB Table
Column
|
Type
| Modifiers
----------+-----------------------+--------EMPID (PK) name salary email
| | | |
int varchar(50) double varchar(50)
| not null | not null | |
12
First trip to Hibernate World Hibernate configuration property file
Used for configuring hibernate Contains - Database Configuration - Datasource Configuration - Transaction Configuration - Caching Configuration - ConnectionPool Configuration - Other Settings.
13
First trip to Hibernate World Hibernate Configuration
14
First trip to Hibernate World The hibernate-mapping configuration file
Object to relation mappings are often defined in a xml file Mapping file can be hand written or edited. Java Centric persistence classes. No of tools available to generate the configuration. -AndroMDA -XDoclets -Middlegen Standard DTD for correct implementation
15
First trip to Hibernate World Hibernate XML Configuration Employee.hbm.xml
16
First trip to Hibernate World Persisting the Employee SessionFactory sf = Configuration.configure().buildSessionFactory(); Session session = sf.OpenSession(); Transaction tx = session.beginTransaction(); Employee emp = new Employee() emp.setEmail(“
[email protected]”); emp.setName(“Gopal Patel”); emp.setSalary(“13331”); session.save(emp); Tx.commit(); session.close();
17
First trip to Hibernate World Loading the Employee Try{ SessionFactory sf = Configuration.configure().buildSessionFactory(); Session session = sf.OpenSession(); Transaction tx = session.beginTransaction(); Employee emp = session.get(Employee.Class, new Long(1)); System.out.println(“Employee salary : ” + emp.getSalary()); Tx.commit(); }Catch(HibernateException e){ e.printStackTrace(); }
18
Hibernate Architecture
Hibernate Architecture Responsibilities of architecture -Manage connection with the database -Converts HQL (Hibernate Query Language) statements to database specific statement. -Manage result set on its own. -Performs mapping of these database specific data to Java objects which are directly used by Java application.
20
Hibernate Architecture Elements
21
Hibernate Architecture – Core Interfaces
Hibernate Core interfaces
Session interface
SessionFactory Interface
Hibernate session can be termed as a collection of loaded objects relating to a single unit of work. This Is the primary interface used by the Hibernate application. Hibernate Session are not thread safe hence by design be used one session per thread.
Hibernate Session provider Single instance per application/data source. Caches generated SQL statements and other mapping metadata.
Configuration Interface
The Configuration object is used to configure and bootstrap Hibernate. Application uses Configuration instance to specify the location of mapping files.
22
Hibernate Architecture Core Interfaces
Transaction Interface
Query and Criteria Interfaces.
The Transaction interface is an optional API. User might choose to use JDBC Tx, JTA Abstracts the application code by the underlying transaction implementations. Helps to keep hibernate application portable between different kind of execution environments.
Manages and controls query execution Queries can be written in HQL or in native SQL. Criteria interfaces allows you to create execute object oriented criteria queries.
Callback interfaces
Allow the application to receive notification when a transaction happens to an object. Eg. when the object is loaded, deleted, saved. Hibernate interfaces are not needed to be implemented but are useful sometimes.
Types
Extension Interfaces
Interfaces that allow extension of Hibernate’s powerful mapping functionality, such as UserType, CompositeUserType, and IdentifierGenerator.
23
Hibernate Architecture Elements General steps: /* Load the Hibernate configuration file and create configuration object. It will automatically load all hbm mapping files. */ Configuration cfg = new Configuration(); cfg.configure(CONFIG_FILE_LOCATION);
/* Create session factory from configuration object */ SessionFactory sessionFactory = cfg.buildSessionFactory();
/* Get one session from this session factory. */ Session session = sessionFactory.openSession();
/* Create HQL query. */ Query query = session.createQuery("from EmployeeBean”);
/* Execute query to get list containing Java objects. */ List<EmployeeBean> finalList = query.list();
24
Persistent classes »Persistent
classes are classes in an application that implement the entities of the business problem »Examples:
Employee Customer Order Item
»Hibernate
persistent classes implement POJO fundamentals
25
Rules »Implement
Required for runtime proxy generation using Constructor.newInstance() Constructor must have atleast package visibility
»Provide
non-final classes (optional)
Mandatory for proxying Performance tuning
»Declare
an identifier property (optional)
Some functionalities (transitive persistence) require identifier Consistently-named Nullable (Non-primitive) type
»Prefer
a no-argument constructor
getters & setters for persistent fields (optional)
Can persist a property with default, protected or private get/set pair
26
POJO example public class User implements Serializable { private Long id; private String username; private Address address; public User() {} public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; …. } public MonetaryAmount calcShippingCosts(Address fromLocation) { ... }
//Implements serializable //Identifier property
//No – arg constructor //Accessor methods
//Some Logic
//Business method
}
27
Rules »Implement
equals & hashCode() methods
Hibernate guarantees equivalence of objects only in session scope Necessary for scenarios where instances are stored in a Set or are reattached to the session Implement using business key equality
Not null Unique Rarely changes
28
Rules public class User { ... public boolean equals(Object other) { if (this==other) return true; if ( !(other instanceof User) ) return false; final User that = (User) other; return this.username.equals( that.getUsername() );
} public int hashCode() { return username.hashCode(); }
} 29
Implementing Inheritance public class ATMCardUser extends User { private String cardNbr; public String getCardNbr(){ … } protected void setCardNbr(){ … } } »Observes first and second rules »Inherits identifier property from super class 30
Dynamic Models »Dynamic
Modes
Set default_entity_mode Uses map Can be set on SessionFactory or on per session basis
31
Example
<property name="name“ column="NAME" type="string"/> <property name="address“ column="ADDRESS" type="string"/>
Example Map david = new HashMap(); david.put("name", "David"); david.put(“address", “….."); session.save("Customer", david);
What is a Transient Object?
I want to insert a new User into the database!!!
Create a new User object User newUser = new User(); newUser.setUserName(“Gopal”); newUser.setEmailId(“[email protected]”);
34
What is persistent Object?
Obtain session object and save newUser
SessionFactory sf = Configuration.configure().buildSessionFactory(); Session session = sf.OpenSession(); Transaction tx = session.beginTransaction(); session.save(newUser); System.out.println(newUser.getId());
tx.commit(); session.close();
35
What is a detached object?
After the session is closed, I want the id. System.out.println(newUser.getId());
36
Persistence Lifecycle
37
Transient objects
Not associated with database, table or row If not referenced, they are inaccessible and valid for garbage collection They are non-transactional To convert transient object to persistent object
Call to save() or saveOrUpdate() creation of a reference from an already persistent instance.
38
Persistent Objects
Any instance with a database identity Associated with a Session and are transactional State is synchronized with the database at various instances and changes are propagated Automatic Dirty Checking Call to delete() makes a persistent object transient. 39
Detached Objects
Instances lose their association with persistence manager when session is closed They contain persistent data (which might be stale later) State is no longer guaranteed to be synchronized with db state Can be re-associated with a session again using session.lock() Explicit detachment operation is also provided by hibernate, Session.evict()
40
Update persistent state of detached object user.setEmailId(“[email protected]”); Session sess = sessionFactory.openSession(); Transaction tx = sess.beginTransaction(); sess.update(user); user.setEmailId(“[email protected]”); tx.commit(); sess.close();
//Without forcing an update Session sessionTwo = sessions.openSession(); Transaction tx = sessionTwo.beginTransaction(); sessionTwo.lock(user, LockMode.NONE); user.setPassword("secret"); user.setLoginName(“David"); tx.commit(); sessionTwo.close();
41
Retrieving a persistent object
Session.load()
//Get the object with a given identifier long id = 1 User user = (User) session.load(User.class, new Long(id)); //Load state of user in a new object of your own User newUser = new User(); Session.load(newUser, new Long(id));
Used when a row with given identifier definitely exist in database
42
Exercise!!! Session sess = factory.openSession(); Transaction tx = sess.beginTransaction(); Object user1 = sess.load(User.class,new Long(1)); Object user2 = sess.load(User.class,new Long(1)); If (user1==user2) System.out.println(“identical”);
Tx.commit();
sess.close();
Sess2 = factory.openSession(); Transaction tx2 = sess2.beginTransaction(); Object user3 = sess2.load(User.class,new Long(1)); If(user3==user2) System.out.println(“identical 2”); Else System.out.println(“Not identical”); Tx2.commit(); sess2.close(); 43
Retrieving a persistent object
Session.get()
//Get the object with a given identifier long id = 1 User user = (User) session.get(User.class, new Long(id));
Used when we are not sure that a row with given identifier exist in the database Returns null if row doesn’t exist
44
Re-loading persistent object session.refresh(); sess.save(user); sess.flush(); //force the SQL INSERT sess.refresh(user);
Generally used when database triggers are used to initialize some of the properties of an object Loads the object, synchronizes with the DB.
45
Updating a persistent object Session session = sessions.openSession(); Transaction tx = session.beginTransaction(); int userID = 1234; User user = (User) session.get(User.class, new Long(userID)); //Automatic dirty checking user.setPassword("secret");
tx.commit(); session.close();
46
Making objects Transient //Making Persistent Object Transient Session session = sessions.openSession(); Transaction tx = session.beginTransaction(); int userID = 1234; User user = (User) session.get(User.class, new Long(userID)); session.delete(user);
tx.commit(); session.close(); //Making Detached Object Transient Session session = sessions.openSession(); Transaction tx = session.beginTransaction(); session.delete(user); tx.commit(); session.close(); 47
Flushing Session session.flush()
Session will execute the SQL statements needed to synchronize the JDBC connection'sstate with the state of objects held in memory. Executed at following points:
before some query executions from org.hibernate.Transaction. from Session.flush() SQL fired in following order all entity insertions, in the same order the corresponding objects were saved using Session.save() all entity updates all collection deletions all collection element deletions, updates and insertions all collection insertions all entity deletions, in the same order the corresponding objects were deleted using Session.delete()
48