Loading presentation...

Present Remotely

Send the link below via email or IM

Copy

Present to your audience

Start remote presentation

  • Invited audience members will follow you as you navigate and present
  • People invited to a presentation do not need a Prezi account
  • This link expires 10 minutes after you close the presentation
  • A maximum of 30 users can follow your presentation
  • Learn more about this feature in our knowledge base article

Do you really want to delete this prezi?

Neither you, nor the coeditors you shared it with will be able to recover it again.

DeleteCancel

Make your likes visible on Facebook?

Connect your Facebook account to Prezi and let your likes appear on your timeline.
You can change this under Settings & Account at any time.

No, thanks

Hibernate Workshop

This is a workshop for VILTians
by

Alvaro Amor

on 14 May 2010

Comments (0)

Please log in to add your comment.

Report abuse

Transcript of Hibernate Workshop

1. Introduction

2. Modules and Architecture

3. Configuration

4. Persistent Classes

5. O/R Mapping

6. Inheritance

7. Working with objects

8. Transactions & Concurrency

9. Interceptors

10. HQL & Criteria Queries

11. Improving performance

12. Best practices
Arquitectura de una aplicación J2EE
Presentación - Interfaz de usuario
Aplicación - Flujo de navegación
Dominio - Modelo y logica de negocio
Persistencia - De los objetos del dominio
J2EE application architecture
Presentation - User interface
Application - Navigation flow
Domain - Model and business logic
Persistence - Domain objects store
Persistence
Relational Data Base Management System (RDBMS) - MySQL, Oracle, SQL Server...
Object Oriented Data Base Management System (OODBMS) - Oracle
Java Data Base Connectivity (JDBC)
Object Relational Mapping (ORM)
ORM Elements
API with basic operations
Query language
Object - Database mapping
Transactions
Dirty checking, lazy loading
Advantages
Productivity
Maintenance
Performance
Database independence
ORM Solutions
Hibernate
iBatis
JPA
Hibernate Modules
Hibernate Core
Hibernate Annotations
Hibernate Entity Manager
Hibernate Shards
Hibernate Search
Development Process
Bottom-up (hbm2hbmxml, hbm2java)
Top-down (hbm2dll)
Middle-out
Basic Architecture
Basic Components
SessionFactory (thread-safe, mappings cache, second-level cache)
Session (unit work, persistence manager, transaction factory, first-level cache)
Persistent objects (persistent state and business function, associated with a session)
Transient and detached objects (instances not associated with a session, created by application or by a closed session)
Transaction (atomic units of work, abstracts from transaction type: JDBC, JTA, CORBA)
ConnectionProvider (factory and pool for JDBC connections)
TransactionFactory

Configuration (mapping loader)
Query
Criteria
Configuration
hibernate.cfg.xml
Mapping files references
Database dialect
Database connection
Connection pool properties
show_sql and format_sql
Instance states
Transient - The instance is not associated with any persistence context. It has no persistent identity or primary key value.
Persistent - The instance is currently associated with a persistence context. It has a persistent identity (primary key value) and can have a corresponding row in the database.
Detached - The instance was once associated with a persistence context, but that context was closed, or the instance was serialized to another process.
hibernate.cfg.xml sample
hibernate.connection.driver_class - JDBC driver class
hibernate.connection.url - JDBC URL
hibernate.connection.username - database user
hibernate.connection.password - database user password
hibernate.connection.pool_size - maximum number of pooled connections
hibernate.c3p0.* - Properties for C3P0 pool (min_size, max_size...)
hibernate.connection.datasource - datasource JNDI name
hibernate.jndi.url - URL of the JNDI provider
hibernate.jndi.class - class of the JNDI InitialContextFactory
hibernate.jdbc.fetch_size - A non-zero value determines the JDBC fetch size (calls Statement.setFetchSize()).
hibernate.jdbc.batch_size - A non-zero value enables use of JDBC2 batch updates by Hibernate.
hibernate.jdbc.batch_versioned_data - Set this property to true if your JDBC driver returns correct row counts from executeBatch().
hibernate.jdbc.factory_class - Select a custom org.hibernate.jdbc.Batcher.
hibernate.jdbc.use_scrollable_resultset - Enables use of JDBC2 scrollable resultsets by Hibernate.
hibernate.jdbc.use_streams_for_binary - Use streams when writing/reading binary or serializable types to/from JDBC.
hibernate.jdbc.use_get_generated_keys - Enables use of JDBC3 PreparedStatement.getGeneratedKeys() to retrieve natively generated keys after insert.
hibernate.connection.provider_class - The classname of a custom org.hibernate.connection.ConnectionProvider which provides JDBC connections to Hibernate.
hibernate.connection.isolation - Sets the JDBC transaction isolation level. Check java.sql.Connection for meaningful values, but note that most databases do not support all isolation levels and some define additional, non-standard isolations.
hibernate.connection.autocommit - Enables autocommit for JDBC pooled connections (it is not recommended).
hibernate.connection.release_mode - Specifies when Hibernate should release JDBC connections. By default, a JDBC connection is held until the session is explicitly closed or disconnected. For an application server JTA datasource, use after_statement to aggressively release connections after every JDBC call. For a non-JTA connection, it often makes sense to release the connection at the end of each transaction, by using after_transaction. auto will choose after_statement for the JTA and CMT transaction strategies and after_transaction for the JDBC transaction strategy.
hibernate.connection.<propertyName> Pass the JDBC property <propertyName> to DriverManager.getConnection().
hibernate.jndi.<propertyName> Pass the property <propertyName> to the JNDI InitialContextFactory.
JDBC and Connection properties
hibernate.dialect - The classname of a Hibernate org.hibernate.dialect.Dialect which allows Hibernate to generate SQL optimized for a particular relational database.
hibernate.show_sql - Write all SQL statements to console. This is an alternative to setting the log category org.hibernate.SQL to debug.
hibernate.format_sql - Pretty print the SQL in the log and console.
hibernate.default_schema - Qualify unqualified table names with the given schema/tablespace in generated SQL.
hibernate.default_catalog - Qualifies unqualified table names with the given catalog in generated SQL.
hibernate.session_factory_name - The org.hibernate.SessionFactory will be automatically bound to this name in JNDI after it has been created.
hibernate.max_fetch_depth - Sets a maximum "depth" for the outer join fetch tree for single-ended associations (one-to-one, many-to-one). A 0 disables default outer join fetching.
hibernate.default_batch_fetch_size - Sets a default size for Hibernate batch fetching of associations.
hibernate.default_entity_mode - Sets a default mode for entity representation for all sessions opened from this SessionFactory
hibernate.order_updates - Forces Hibernate to order SQL updates by the primary key value of the items being updated. This will result in fewer transaction deadlocks in highly concurrent systems.
hibernate.generate_statistics - If enabled, Hibernate will collect statistics useful for performance tuning.
hibernate.use_identifier_rollback - If enabled, generated identifier properties will be reset to default values when objects are deleted.
hibernate.use_sql_comments - If turned on, Hibernate will generate comments inside the SQL, for easier debugging, defaults to false.
Properties
Cache properties
hibernate.cache.provider_class - The classname of a custom CacheProvider.
hibernate.cache.use_minimal_puts - Optimizes second-level cache operation to minimize writes, at the cost of more frequent reads. This setting is most useful for clustered caches and, in Hibernate3, is enabled by default for clustered cache implementations.
hibernate.cache.use_query_cache - Enables the query cache. Individual queries still have to be set cachable.
hibernate.cache.use_second_level_cache - Can be used to completely disable the second level cache, which is enabled by default for classes which specify a <cache> mapping.
hibernate.cache.query_cache_factory - The classname of a custom QueryCache interface, defaults to the built-in StandardQueryCache.
hibernate.cache.region_prefix - A prefix to use for second-level cache region names.
hibernate.cache.use_structured_entries - Forces Hibernate to store data in the second-level cache in a more human-friendly format.
Transaction properties
hibernate.transaction.factory_class - The classname of a TransactionFactory to use with Hibernate Transaction API (defaults to JDBCTransactionFactory).
jta.UserTransaction - A JNDI name used by JTATransactionFactory to obtain the JTA UserTransaction from the application server.
hibernate.transaction.manager_lookup_class - The classname of a TransactionManagerLookup. It is required when JVM-level caching is enabled or when using hilo generator in a JTA environment.
hibernate.transaction.flush_before_completion - If enabled, the session will be automatically flushed during the before completion phase of the transaction.
hibernate.transaction.auto_close_session - If enabled, the session will be automatically closed during the after completion phase of the transaction.
Miscellaneous properties
hibernate.current_session_context_class - Supply a custom strategy for the scoping of the "current" Session.
hibernate.query.factory_class - Chooses the HQL parser implementation.
hibernate.query.substitutions - Is used to map from tokens in Hibernate queries to SQL tokens.
hibernate.hbm2ddl.auto - Automatically validates or exports schema DDL to the database when the SessionFactory is created. With create-drop, the database schema will be dropped when the SessionFactory is closed explicitly.
http://docs.jboss.org/hibernate/stable/core/reference/en/html/session-configuration.html
Persistent Classes
A simple POJO
Implementing a no-argument constructor
Providing an identifier property (optional)
Prefer non-final classes to use lazy (optional)
Declaring accessors for persistent fields (optional)
Implementing inheritance
Implementing hashCode() and equals()
O/R Mapping
Basic
Collection
Association
Component
Mapping element attributes
Doctype
hibernate-mapping (schema, catalog, default-cascade, default-access, default-lazy, auto-import, package)
class (name, table, discriminator-value, mutable, schema, catalog, proxy, dynamic-update, dynamic-insert, select-before-update, polymorphism, where, persister, batch-size, optimistic-lock, lazy, entity-name, check, rowid, subselect, abstract)
id (name, type, column, unsaved-value, access)
composite-id (name, class, mapped, access, node)
generator (increment, identity, sequence, hilo, seqhilo, uuid, guid, native, assigned, select, foreign, sequence-identity)
discriminator (column, type, force, insert, formula)
version (column, name, type, access, unsaved-value, generated, insert)
timestamp (column, name, access, unsaved-value, source, generated)
property (name, column, type, update, insert, formula, access, lazy, unique, not-null, optimistic-lock, generated)
many-to-one (name, column, class, cascade, fetch, update, insert, property-ref, access, unique, not-null, optimistic-lock, lazy, not-found, entity-name, formula)
one-to-one (name, class, cascade, constrained, fetch, property-ref, access, formula, lazy, entity-name)
natural-id (mutable)
component, dynamic-component (name, class, insert, update, access, lazy, optimistic-lock, unique)
properties (name, insert, update, optimistic-lock, unique)
subclass (name, discriminator-value, proxy, lazy)
joined-subclass (name, table, proxy, lazy)
union-subclass (name, table, proxy, lazy)
join (table, schema, catalog, fetch, inverse, optional)
key (column, on-delete, property-ref, not-null, update, unique)
column (name, length, precision, scale, not-null, unique, unique-key, index, sql-type, check, default, read, write)
formula
import (class, rename)
any (name, id-type, meta-type, cascade, access, optimistic-lock)
Collection Mapping
Association Mapping
Mapping elements
Doctype - DTD definition
hibernate-mapping - defines common attributes for contained classes
class - declares a persistence class (tables and views)
id - defines the mapping from key property to primary key
composite-id - defines the mapping for a composite primary key
generator - used to generate unique identifiers
discriminator - used for table-per-class-hierarchy mapping strategy
version - indicates that the table contains versioned data
timestamp - indicates that the table contains timestamped data
property - declares a persistent property of the class
many-to-one - represents a many-to-one association to another persistent class
one-to-one - represents a one-to-one association to another persistent class
natural-id - a natural key is a property or combination of properties that is unique and non-null
component - maps properties of a child object to columns of the table of a parent class
dynamic-component - allows a Map to be mapped as a component, where the property names refer to keys of the map
properties - allows the definition of a named, logical grouping of the properties of a class
subclass - used for the table-per-class-hierarchy mapping strategy
joined-subclass - used for the table-per-subclass mapping strategy
union-subclass - used for the table-per-concrete-class strategy
join - used to map properties of one class to several tables that have a one-to-one relationship
key - defines a join to a new table that references the primary key of the original table
column - equals to columns attribute
formula - equals to formula attribute
import - to not specify the fully qualified package name in Hibernate queries
any - defines a polymorphic association to classes from multiple tables
see: http://docs.jboss.org/hibernate/stable/core/reference/en/html/mapping.html#mapping-declaration
Persistent collections (java.util.Set, java.util.Collection, java.util.List, java.util.Map, java.util.SortedSet, java.util.SortedMap)
<set>, <list>, <map>, <bag>, <array> and <primitive-array>
Attributes: name, table, schema, lazy, inverse, cascade, sort, order-by, where, fetch, batch-size, access, optimistic-lock, mutable
Collection foreign keys
Collection elements
Indexed collections
Many-to-many associations
One-to-many associations
Sorted collections
Bidirectional associations
Unidirectional associations: many-to-one, one-to-one, one-to-many
Unidirectional associations with join tables: one-to-many, many-to-one, one-to-one, many-to-many
Bidirectional associations: one-to-many, many-to-one, one-to-one
Bidirectional associations with join tables: one-to-many, many-to-one, one-to-one, many-to-many
Inheritance
Table per class hierarchy - (discriminator, subclass) - One table is required and one discriminator column. Columns declared by the subclasses cannot have NOT NULL constraints
Table per subclass - (joined-subclass | discriminator, subclass, join) - One table for each subclass and one for the parent
Table per concrete class - (union-subclass)
Hibernate Object States
Transient - an object is transient if it has just been instantiated using the new operator, and it is not associated with a Hibernate Session. It has no persistent representation in the database and no identifier value has been assigned. Transient instances will be destroyed by the garbage collector if the application does not hold a reference anymore. Use the Hibernate Session to make an object persistent
Persistent - a persistent instance has a representation in the database and an identifier value. It might just have been saved or loaded, however, it is by definition in the scope of a Session. Hibernate will detect any changes made to an object in persistent state and synchronize the state with the database when the unit of work completes. Developers do not execute manual UPDATE statements, or DELETE statements when an object should be made transient
Detached - a detached instance is an object that has been persistent, but its Session has been closed. The reference to the object is still valid, of course, and the detached instance might even be modified in this state. A detached instance can be reattached to a new Session at a later point in time, making it (and all the modifications) persistent again. This feature enables a programming model for long running units of work that require user think-time
Making objects persistent
Instance a new object (transient)
Get a session
Persist the object - save or persist method (persistent state)
Close the session (detached state)
Loading an object
load method: object or class, plus identifier, throws an exception if there is no matching database row (lazy)
get method: returns null if there is no matching database row (eager)
refresh method: re-load the object
Querying
createQuery("QUERY")
getNamedQuery("query_name") - defined in the mapping file
createFilter(COLLECTION, "QUERY")
Criteria and native SQL queries
uniqueResult(), list(), scroll() or iterate()
Queries can return objects, tuples or scalar results
Bind parameters: named and positional
Pagination: firstResult, maxResults
Modifying objects
Changes in a persistent object are persisted when the session is flushed (load, apply changes, flush)
Detached objects are used for long transactions, and they can be reattached using update, saveOrUpdate, merge or lock (unmodified)
Deleting objects
delete method changes the state from persistent to transient and remove the object from the database
Flushing the session
Occurs: before query executions, on transaction commit and session flush
Flush modes: at commit, automatically or never (flush manually)
Transactions
Unit of work
Do not use session-per-operation, session-per-user-session or session-per-application
Use session-per-request, session-per-request-with-detached-objects or session-per-conversation
Non-managed
// Non-managed environment idiom
Session sess = factory.openSession();
Transaction tx = null;
try {
tx = sess.beginTransaction();

// do some work

tx.commit();
}
catch (RuntimeException e) {
if (tx != null) tx.rollback();
throw e; // or display error message
}
finally {
sess.close();
}
// Non-managed environment idiom with getCurrentSession()
try {
factory.getCurrentSession().beginTransaction();

// do some work

factory.getCurrentSession().getTransaction().commit();
}
catch (RuntimeException e) {
factory.getCurrentSession().getTransaction().rollback();
throw e; // or display error message
}
JTA
// BMT idiom
Session sess = factory.openSession();
Transaction tx = null;
try {
tx = sess.beginTransaction();

// do some work

tx.commit();
}
catch (RuntimeException e) {
if (tx != null) tx.rollback();
throw e; // or display error message
}
finally {
sess.close();
}
// BMT idiom with getCurrentSession()
try {
UserTransaction tx = (UserTransaction)new InitialContext()
.lookup("java:comp/UserTransaction");
tx.begin();

// Do some work on Session bound to transaction

factory.getCurrentSession().load(...);

factory.getCurrentSession().persist(...);

tx.commit();
}
catch (RuntimeException e) {
tx.rollback();
throw e; // or display error message
}
// CMT idiom
Session sess = factory.getCurrentSession();

// do some work
Interceptors & events
The Interceptor interface provides callbacks from the session to the application, allowing the application to inspect and/or manipulate properties of a persistent object before it is saved, updated, deleted or loaded
Event system that uses event listeners
HQL
Object-oriented query languange
Case-insensitive except classes and properties
From clause
Associations and joins
Forms of join syntax
Identifier property
Select clause
Aggregate functions
Polymorphic queries
Where clause
Expressions
Order by clause
Group by clause
Subqueries
Criteria queries
Native SQL
Improving performance
Fetching strategies
Working with lazy associations
Tuning fetch strategies
Single-ended association proxies
Initializing collections and proxies
Using batch fetching
Using subselect fetching
Fetch profiles
Using lazy property fetching
The Second Level Cache
Cache mappings
Strategy: read only
Strategy: read/write
Strategy: nonstrict read/write
Strategy: transactional
Cache-provider/concurrency-strategy compatibility
Managing the caches
The Query Cache
Enabling query caching
Query cache regions
Understanding Collection performance
Taxonomy
Lists, maps, idbags and sets are the most efficient collections to update
Bags and lists are the most efficient inverse collections
One shot delete
Monitoring performance
Monitoring a SessionFactory
Metrics
Best practices
Write fine-grained classes and map them using <component>
Declare identifier properties on persistent classes
Identify natural keys
Place each class mapping in its own file
Load mappings as resources
Consider externalizing query strings
Use bind variables
Do not manage your own JDBC connections
Consider using a custom type
Use hand-coded JDBC in bottlenecks
Understand Session flushing
In a three tiered architecture, consider using detached objects
In a two tiered architecture, consider using long persistence contexts
Do not treat exceptions as recoverable
Prefer lazy fetching for associations
Use the open session in view pattern, or a disciplined assembly phase to avoid problems with unfetched data
Consider abstracting your business logic from Hibernate
Do not use exotic association mappings
Prefer bidirectional associations
Criteria instance
Restrictions build query criterion
Ordering results
Associations
Example queries
Projections, aggregation and grouping
Detached queries and subqueries
Queries by natural identifier
Scalar queries
Entity queries
Handling associations and collections
Returning multiple entities
Returning non-managed entities
Handling inheritance
Parameters
Named SQL queries
Hibernate Core
Hibernate Entity Manager
Hibernate Annotations
Hibernate Shards
Hibernate Search
Hibernate Workshop
by Álvaro Amor
for VILT

JPA 2 Specification (JSR-317)
AnnotationConfiguration
Mapping: class or package
Specific properties:
hibernate.cache.default_cache_concurrency_strategy - Setting used to give the name of the default org.hibernate.annotations.CacheConcurrencyStrategy to use when either @Cacheable @Cache} is used. @Cache(strategy="..") is used to override this default.
hibernate.id.new_generator_mappings - true or false. Setting which indicates whether or not the new IdentifierGenerator implementations are used for AUTO, TABLE and SEQUENCE. Default to false to keep backward compatibility.
javax.persistence.*
@Entity
@Id
@Table
@Version
@Column
@Transient, @Basic, @Enumerated, @Temporal, @Lob
Access type: field or property (be consistent)
@Embedded, @Embeddable, @Access
@OneToOne: @PrimaryKeyJoinColumn, @JoinColumn, @JoinTable
@ManyToOne: @JoinColumn, @JoinTable, targetEntity
@OneToMany: mappedBy
@ManyToMany: @JoinTable
@Inheritance: TABLE_PER_CLASS, SINGLE_TABLE, JOINED
@DiscriminatorColumn, @DiscriminatorValue
@MappedSuperclass, @AttributeOverride, @AssociationOverride
Java Persistence Annotations
What is this??
Concepts
EntityManagerFactory - SessionFactory
EntityManager - Session
Persistence Context (entity instances)
Persistence Unit (entity definitions)
Container-managed Entity Manager
Application-managed Entity Manager
JTA Entity Manager
Resource-local Entity Manager
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("manager1");
Configuration
META-INF/persistence.xml
name
transaction-type
provider
jta-data-source, non-jta-datasource
mapping-file
jar-file
exclude-unlisted-classes
class
shared-cache-mode
validation-mode
properties (timeout, validation, connection)
Entity States
New (transient): an entity is new if it has just been instantiated using the new operator, and it is not associated with a persistence context. It has no persistent representation in the database and no identifier value has been assigned.
Managed (persistent): a managed entity instance is an instance with a persistent identity that is currently associated with a persistence context.
Detached: the entity instance is an instance with a persistent identity that is no longer associated with a persistence context, usually because the persistence context was closed or the instance was evicted from the context.
Removed: a removed entity instance is an instance with a persistent identity, associated with a persistence context, but scheduled for removal from the database.
Operations
entityManager.persist(object)
entityManager.find(class, id) / entityManager.getReference(class, id)
createQuery: JP-QL, SQL or Criteria
entityManager.flush()
entityManager.refresh(object)
entityManager.merge(object)
entityManager.remove(object)
entityManager.contains(object)
Persistence.getPersistenceUtil().isLoaded(object)

Transitive persistence
Locking
Caching
Properties
hibernate.search.default.directory_provider
hibernate.search.default.indexBase

Annotations or FullTextIndexEventListener
@Indexed
@DocumentId
@Field
@Fields
@Analyzer
@FieldBridge
@IndexedEmbedded
@ContainedIn
@TokenizerDef / @TokenFilterDef

FullTextSession fullTextSession = Search.getFullTextSession(session);
Query fullTextQuery = fullTextSession.createFullTextQuery(query);
How to...
Simple architecture
Complex architecture
org.hibernate.Session - org.hibernate.shards.session.ShardedSession
org.hibernate.SessionFactory - org.hibernate.shards.ShardedSessionFactory
org.hibernate.Criteria - org.hibernate.shards.criteria.ShardedCriteria
org.hibernate.Query - org.hibernate.shards.query.ShardedQuery
Similarities
Full transcript