Workshop on Hibernate Authors: Rely-On Solutions People : Process : Technology : Tools
Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com ©©Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Hibernate Workshop
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Agenda • Introduction to Hibernate- 60 mins. – Overview of ORM solutions – Hibernate Architecture – Persistence lifecycle • Transient, Persistent and Detached objects
– Object and database identity • Identity Scope
• Getting Started- 120 mins. – Web application example setup • Hibernate configuration • Configuration Strategies
– Mappings • Mapping attributes • Lab 1 – Setting up web application – Setup a basic User object
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Agenda
(contd.)
• Relationships- 120 mins – Unidirectional and bi-directional relationships – One-to-one • Lab- User has ContactInfo
– One-to-many & Many-to-one • Lab- Group to User
– Many-to-many • Lab- Items and Categories • Lab- Categories and child categories
– Simple inheritance relationship • Lab- BillingDetails and CreditCard and BankAccount
• Basic Queries- 30 mins – get() and load() – Named Queries
• • • • •
Lab- Simple User Authentication- 45 mins Intro to TDD and DBUnit- 30 mins. Summary- 15 mins Q&A- 30 mins Feedback- 10 mins
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Overview of object-relational mapping
• Mapping tables to Java Objects? Is it that simple? • Paradigm mismatch – Problem of granularity
Coarse grained User to fine-grained Address objects. Are tables as flexible as our Java type system?
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
– Problem of subtypes
RDBMS: No direct way to represent inheritance.
How to represent polymorphic associations in RDBMS?
-Table per class? -Table per class hierarchy with discriminator columns? -Table per subclass?
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
– Problem of identity
Java Identity •Object identity •Equality as determined by the implementation of the equals() method Database Identity •Primary Keys (surrogate or natural)
Is equals() or == naturally equivalent to the primary key value?
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
- Problems relating to associations Java Associations • directional object references (bi-directionality has to be explicitly coded) •Multiplicity not very obvious •Concept of object graph navigation •Link tables?? Databases Associations •Foreign Keys •No concept of directionality. No meaning of navigation. Table joins and projection. •Multiplicity very obvious (one-to-one, one-to-many) •Many-to-many using link tables.
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
– Problem of object graph navigation Walking the object graph in Java •aUser.getBillingDetails().getAccountNumber()
Walking the RDBMS graph? •N+1 selects problem • requires execution of one select statement for each node of the object graph
Bottom Line: Objects cant be mapped directly to RDBMS. Hence Hibernate!
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Hibernate Architecture 5 Core interfaces • Session Interface •SessionFactory Interface •Configuration Interface •Transaction Interface •Query and Criteria interface
Other Interfaces •Callback interfaces •Types •Extensions interface
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Core Interfaces • Session (persistence manager) – – – –
Lightweight Inexpensive to create and destroy NOT thread safe. Session per thread. Use ThreadLocal. Responsibilities • • • •
Basic CRUD operations Query execution Control of transactions Management of transaction-level cache
• SessionFactory – NOT lightweight (one per database) – Thread safe – Caches generated SQL statements and Hibernate metadata
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Core Interfaces
(contd.)
• Configuration – Configure and bootstrap Hibernate – Creates SessionFactory – For both managed and non-managed environement
• Transaction – Optional API. Hibernate might choose to use JDBC, JTA UserTransaction interface or CORBA transactions
• Query and Criteria – – – –
Perform queries Object-oriented criteria queries Lightweight, not thread safe. Cant be used outside Session that created it.
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Other Interfaces • CallBack – React to events in the persistence lifecycle – Pollutes persistence classes with non-portable code – Use Interceptor interface instead
• Types – Maps java types to database types spanning multiple columns – Entity type and value-types or scalar types – User-defined custom types (UserType and CompositeUserType)
• Extension Interfaces – – – – – – – – –
Primary key generation (IdentifierGenerator interface) SQL dialect support (Dialect abstract class) Caching strategies (Cache and CacheProvider interfaces) JDBC connection management (ConnectionProvider interface) Transaction management (TransactionFactory, Transaction, and TransactionManagerLookup interfaces) ORM strategies (ClassPersister interface hierarchy) Property access strategies (PropertyAccessor interface) Proxy creation (ProxyFactory interface)
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Persistence Lifecycle Transient Objects - aren’t associated with any DB table row. - Non-transactional - state lost when de-referenced
Persistent Objects - any instance with a database identity - always associated with a Session - transactional - automatic dirty checking Detached Objects - Persistent objects after close() - state synchronization no longer guaranteed with DB state. -Can be reattached to another Session to synch with DB. - avoid the DTO (anti-) pattern by using detached objects © Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Scope of Object Identity • no identity scope – no guarantees that if a row is accessed twice, the same Java object instance will be returned to the application.
• transaction-scoped identity – guarantees that, in the context of a single transaction, there is only one object instance that represents a particular database row.
• process-scoped identity – guarantees that there is only one object instance representing the row in the whole process (JVM).
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Scope of Object Identity (contd.)
Is a==b?
Is a==b1? What about equals()? © Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Hibernate web application setup Quick Setup - Unzip hibernatex.x.zip - Place everything in hibernate lib to web-application lib. - place jdbc driver jar in web-app lib - create/edit hibernate.cfg.xml - create/edit log4j.properties
What about web-app context setup? Define myApp.xml in $tomcat_home/conf/Catalina/localhost © Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Hibernate Configuration • Managed Environments – Application servers (JBoss, Weblogic) – Allows declarative style of configuration (xml based) – App servers handles resource pools, security, transactions
• Non-managed environment – Concurrency management via thread pooling – Command-line, tomcat servlet engine – Hibernate handles connections and transactions.
Q) How to ‘start’ Hibernate? Ans: Create a SessionFactory from Configuration.
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Configuration of Hibernate Create new Configuration object. Add mapping files. Set properties file.(Default- hibernate.cfg.xml) Create new SessionFactory object.
How do u have multiple mappings? Item.hbm.xml Category.hbm.xml Bid.hbm.xml
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Configuration of Hibernate (contd.) • Place a file called hibernate.properties in the classpath. • Include <property> elements in hibernate.cfg.xml in the classpath. • Define tomcat DataSource in server.xml. Use hibernate.cfg.xml file to define app specific configurations. Create the SessionFactory from a Configuration and store it in your own implementation of a singleton registry. Every execution thread calls this singleton and retrieves the SessionFactory to create a Session.
How do you configure Session and SessionFactory with JNDI?
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Configuration of Hibernate Session server.xml
- read-only JNDI context - Hibernate can not bind its SessionFactory to JNDI. WHY NOT? Session session=sessions.openSession();
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Hibernate.cfg.xml
JDBC Properties
Optional debugging properties
Mapping files.
// Use default hibernate.cfg.xml
sessionFactory = new Configuration().configure().buildSessionFactory(); © Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Configuring SessionFactory -Use server.xml , and -have to use a class which implements javax.naming.ObjectFactory. -There is no class in Hibernate that implements it. How to associate a SessionFactory with a Tomcat JNDI context?
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Configuring SessionFactory (contd.) Use the Global resource in the web application.
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Important Configuration Parameters Hibernate JDBC Properties hibernate.connection.driver_class = com.mysql.jdbc.Driver hibernate.connection.url = jdbc:mysql://localhost/corbus hibernate.connection.username = myuser hibernate.connection.password = secret hibernate.c3p0.min_size=5 C3P0 Connection Pool Configuration hibernate.c3p0.max_size=20 hibernate.c3p0.timeout=1800 hibernate.c3p0.max_statements=50 Identifies which DB to use. hibernate.dialect = net.sf.hibernate.dialect.MySQLDialect
Hibernate Datasource Properties Defined in server.xml
hibernate.connection.datasource = java:/comp/env/jdbc/MyDB hibernate.transaction.factory_class = net.sf.hibernate.transaction.JTATransactionFactory hibernate.transaction.manager_lookup_class = net.sf.hibernate.transaction.JBossTransactionManagerLookup
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Other Configuration Parameters Log4J.properties log4j.logger.net.sf.hibernate.SQL=debug log4j.logger.net.sf.hibernate.type=info log4j.logger.net.sf.hibernate.tool.hbm2ddl=debug log4j.logger.net.sf.hibernate.cache=debug log4j.logger.net.sf.hibernate.connection.DriverManagerConnectionProvider=trace Implementing a NamingStrategy -specify ‘naming strategy’ like table prefixes -Processing ‘logical’ column and table names into ‘physical’ table and columns names
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Leakage of ‘Concerns’ • domain model should be “concerned” only with modeling the business domain • cross-cutting concerns in the classes that implement the domain model. • EJB container prevents leakage of certain cross-cutting concerns using interception – EJB specification imposes many rules and restrictions on how you must implement a domain model. – Non-portable business model – the concerns of the container implementer have leaked – access your domain model via a session bean
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Mapping Persistence Classes Corbus Auction Domain Model
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Development Process • Setup the java project • Setup hibernate.cfg.xml and other infrastructure code like log4j, build.xml etc. • Write POJO. • Write .hbm.xml file • Compile and run unit tests
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Writing POJO Rules of POJO - Implement Serializable - Implement empty constructor - Provide identifier property (OP) - Prefer non-final classes (OP) - Implement equals and HashCode
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Implementing equals() and hashCode()
The problem: - database identity alone does not guarantee object identity - preserve semantics of object Collections - use objects across multiple sessions Why do u need to address it? - intend to put instances of persistent objects in a Set (manyvalued associations)
- intend to use reattachment of detached instances How to do it? - implement equals and hashCode() using ‘business key equality’ eg: username+createDate - don’t use database identity. Instead use a combination of unique, immutable attributes.
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Implementing equals() and hashCode() (contd.) EqualsBuilder HashCodeBuilder
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
CompareToBuilder ToStringBuilder
Mapping Metadata
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Mapping Metadata hibernate-mapping - schema - default-cascade - auto-import - package class - name - table - mutable - dynamic-update - dynamic-insert - select-before-update - lazy
id - name - type - column - unsaved-value generator - class= “native | identity | sequence | hilo | seqhilo | uuid.hex | uuid.string | increment | assigned | foreign”
property - name - column - type - update - insert - formula - access
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Generator Algorithms •
increment
•
identity
•
sequence
•
hilo
•
seqhilo
•
uuid.hex
•
uuid.string
•
native
•
assigned
•
foreign
-
– – – – – – – – – – – – – – – – –
type long, short or int Unique only when no other process is inserting data into the same table. Do not use in a cluster. type long, short or int. identity columns in DB2, MySQL, MS SQL Server, Sybase and HypersonicSQL. type long, short or int uses a sequence uses a hi/lo algorithm type long, short or int, given a table and column uses a hi/lo algorithm type long, short or int, given a named database sequence. uses a 128-bit type string, unique within a network (the IP address is used). The UUID is encoded as a string of hexadecimal digits of length 32. uses the same UUID algorithm. Type string of length 16 consisting of (any) ASCII characters. picks identity, sequence or hilo depending upon the capabilities of the underlying database. lets the application to assign an identifier to the object before save() is called. uses the identifier of another associated object. used in conjunction with a primary key association.
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Entity and Value Types • Entity type - database identity (primary key value). An object reference to an entity is persisted as a reference in the database (a foreign key value). - has its own lifecycle; it may exist independently • Value Type – no database identity; it belongs to an entity, – persistent state is embedded in the table row of the owning entity no – identifiers or identifier properties. – lifespan bounded by the lifespan of the owning entity.
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Mapping Components
Object Composition
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Relationships • Hibernate relationships are inherently unidirectional – Bid to Item is different from Item to Bid
• Multiplicity – One-to-one, many-to-one, one-to-many, many-to-many
Problem - How to represent Item and Bid in Hibernate?
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Unidirectional many-to-one
Many-to-one Mapping for Bid Foreign Key to Bid
One-to-Many Mapping for Item Set of Bids
Bi-directional many-to-one © Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Many-to-one Problem of two different in-memory representations of the same foreign key value: - the item property of Bid and - an element of the bids collection held by an Item. What happens when we add a new bid? Hibernate doesn’t transparently detect the fact that the two changes refer to the same database column, since at this point we’ve done nothing to indicate that this is a bi-directional association.
Mirror image of the collections on the other side.
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
One-to-one using Foreign key association
One-to-One
Mapping for User Foreign Key to User
This ensures that there are no duplicates.
Mapping for Address
What about HomeAddress? © Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
One-to-one using Primary key association Mapping for Address
One-to-One
Mapping for User
Foreign key constraint on the primary key of Address Primary key as foreign key in Address
Mapping for Address ensure that newly saved instances of Address are assigned the same identifier value as their User
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Mapping Collections No duplicates allowed
Addition of index column
Duplicates allowed.
Duplicates allowed.
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Sorted and Ordered Collections Naturally sorted Map.
sorted Map using SQL sorting
Custom sorted Map.
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Many-to-many unidirectional many-to-many association the link table or association table.
Link table will have foreign keys of the CATEGORY and ITEM tables.
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Bi-directional many-to-many association
Many-to-many
Have to set the b-directionality in java.
Inverse side of the association
What kinds of collections may be used for bi-directional many-to-many associations? Do you need to use the same type of collection at each end? © Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Queries • DB insert – session.save(user)
• DB update – session.update(user) – Session.lock(user)
• DB select – Session.get(User.class,userId) – Session.load(User.class,userId)
• DB delete – Session.delete(user);
How to save an entire object graph?
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Transitive Persistence Propagate persistence to detached and transient sub graphs automatically Persistence by Reachability
Persistence by Cascade Cascade=“none”- ignore associations Cascade=“save-update”- navigate during save() and update() Cascade=“delete”- navigate during delete() Cascade=“all”- navigate for saveOrUpdate, delete, evict and lock Cascade=“all-delete-orphan”- same as ‘all’. Also delete dereferenced entities Cascade=“delete-orphan”- delete only dereferenced entities.
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Retrieving objects • • • • •
Retrieve by identifier Retrieve by NamedQuery Use HQL to retrieve objects Use Criteria APIs Use native SQL queries Retrieve by identifier
Load vs get -Load throws exception when object not found; get returns null; - load may return a proxy; get never returns a proxy
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Retrieving objects Named Queries Define the query in the mapping (User.hbm.xml)
Retrieve the query in a session by its name. Set the parameters Execute query
© Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com
Introducing HQL • • • •
Object oriented dialect for SQL Not a data-manipulation language like SQL. Only for object retrieval, not for update, insert or deleting data. Queries by objects NOT tables
-apply restrictions to properties of associated objects related by reference or held in collections -The ability to retrieve only properties of an entity or entities, without the overhead of loading the entity itself in a transactional scope -The ability to order the results of the query -The ability to paginate the results -Aggregation with group by, having, and aggregate functions like sum, min, and max. -Outer joins when retrieving multiple objects per row -Subqueries and called user-defined SQL functions © Rely-On 2005; For further information on Rely-On, please visit www.rely-ongroup.com