ORM with Hibernate

Layered architecture:
– defines interfaces for various concerns (presenstation, business logic and persistance)
– layers communicate from top do bottom
– layer are dependent only on the layer directly below it and the are unaware of any other layers

Presentation – topmost layer, UI (user interface) logic responsible for presentation, control of page and screen navigation
Business – implementing business rules or system requirements, it may have its own business domain entities or reuse the model defined by the persistence layer
Persistence – responsible for storing and retrieving data from one or more data stores (e.g. database), this layer includes the business domain entities (necessarily at least metadata model)

Every application has a set of interceptors, infrastructural helper or utility classes that are used in every layer (e.g. Exception classes for error handling), they don’t form a layer (outside layers).

DAO pattern (data access object) – hide complex JDBC code and non-portable SQL from business logic.

In high concurrency web and enterprise application, serialization cannot be used as a persistence mechanism because it isn’t possible to retrieve any data without deserializing the entrire stream. It cannot be used in an arbitrary search or aggregation of large datasets. It’s even not possible to access or update a single object or subset independently.

ORM (object/relational mapping) – automated and transparent persistence of objects in Java application to the tables in the relational database, using metadata that describes the mapping between the objects and the database.

ORM has an API for:
– basic operations: create, read, update and delete on object of persisted classe
– queries referring classes and properties of classes
– mapping metadata
– interact with transactional objects to perform dirty checking, lazy association fetching and other optimization functions.

Full ORM automatically creates SQL from a metadata-based description.
Efficient access to relational data is usually accomplished via table joins. You should avoid the n+1 selects problem and the Cartesian product problem (fetching to much data in a single select)
Object-oriented application usually access data by naviagating an object network (field.get…().get…()).

ORM advantages:
– no messy SQL
– no tedious persistence related code
– lets you focus on business logic
– fewer lines of code:
— system more understandable (focus on business problem)
— easier to refactor
– no tight coupling between relational representation and domain model (easier to change)
– written by performance experience people
– optimized for different databases

The persisted class should contain the identifier attribute (e.g. long Id with respective setters and getters) to allow the application to access database identity – the primary key value – of a persistent object. If two instances have the same identifier value, they represent the same row in the database.
No-argument constructor is a requirement (Hibernate use reflection on this constructor to instantiate objects).

in src package (src/main/java/com/bawi/… or src/main/resources/com/bawi…)
– A.java
– A.hbm.xml (mapping file for class A)
in src folder (src/main/java or resources)
hibernate.cfg.xml (configures datasource: driver, db connection settings, sql dialect, schema autogeneration … and imports the mapping files *.hbm.xml)

Hibernate is usually initialized by building SessionFactory object (build only once – single instance, thread save, can be shared) from a Configuration object which is a representation of a configuration file. First the hibernate.properties in root of classpath is read, then hibernate.cfg.xml. Latter overrides the former.

SessionFactory sessionFactory =
new Configuration() //read /hibernate.properties
.configure() //or .configure("/a/b.hbm.xml") to read /hibernate.xml or /a/b.hbm.xml
.setProperty(Environment.HBM2DDL_AUTO, "create") //optional to add/override existing conf
.addResource("a/c.hbm.xml") //optional to add/override existing mapping

Hibernate Session – a single threaded non-shared object that represents a particular unit of work with the database. You can call store and load methods on the session object.

Transaction – you can programmatically set transation boundaries (via session.beginTransaction() and transaction.commit()), but it is optional.

HQL – object-oriented (hibernate) query language

Automatic dirty checking – load object via session.get(...), modify loaded object via setters – hibernate will detect changes in object state and automatically update database (execute update sql query) without explicit save().

Cascading save – if already persisted object will get the reference to the new object, then the new object will be automatically persisted (without explicit save()).

transactional write-behind – Hibernate reorders internally SQL statements in order to avoid foreign key violations.

Connection pooling
Instead of creating a connection to the database every time you want to do a unit of work, you should reuse connection from the connection pool – request a connection and return it back to the pool when finished. Acquiring connection from database is expensive (some databases create even a new server process for each connection). Connection pool:
– maintain idle connections (removes unused connections after timeout)
– cache prepared statements across requests for a connection (prepared statements are expensive to create)
Connection pooling can be provided by the application server, by the application itself or via 3rd party library.

With Hibernate a client doesn’t directly request the connection pool, but call hibernate session,query and transaction, hibernate manages database connection pooling for you.
Unmanaged application runtime = without any application server.

Hibernate execute SQL statements asynchronously, usually when the transaction is committed.

Hibernate EntityManager (JPA compliant)
It is a wrapper around Hibernate Core that provides JPA programming interfaces. Create persistence.xml defining persistence unit and connection properties. The hibernate hbm.xml and/or java annotated  files are automatically scanned which can be very handy in big projects. Provides standarized and simplified configuration.

The JMX specification defines the following components:
■ The JMX MBean—A reusable component (usually infrastructural) that
exposes an interface for management (administration)
■ The JMX container—Mediates generic access (local or remote) to the MBean
■ The JMX client—May be used to administer any MBean via the JMX container


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s