Browse DevX
Sign up for e-mail newsletters from DevX


Simplify Java Object Persistence with Hibernate : Page 3

The 'impedance mismatch' between relational databases' tabular orientation and object-oriented Java's hierarchical one is a perennial problem for which the Java world has several good solution offerings. The second in a three-part series, this article examines the ways that the Hibernate framework attempts to simplify the chore of connecting relational databases and the Java programming language.




Building the Right Environment to Support AI, Machine Learning and Deep Learning

Hibernate Sessions
In order to make use of Hibernate's persistence mechanisms, you must initialize the Hibernate environment and obtain a Session object from Hibernate's SessionFactory class. The following snippet of code illustrates these processes:

// Initialize the Hibernate environment Configuration cfg = new Configuration().configure(); // Create the session factory SessionFactory factory = cfg.buildSessionFactory(); // Obtain the new session object Session session = factory.openSession();

The call to Configuration().configure() loads the hibernate.cfg.xml configuration file and initializes the Hibernate environment. Once the configuration is initialized, you can make any additional modifications you desire programmatically. However, you must make these modifications prior to creating the SessionFactory instance.

An instance of SessionFactory is typically created once and used to create all sessions related to a given context.

A Hibernate Session object represents a single unit-of-work for a given data store and is opened by a SessionFactory instance. You must close Sessions when all work for a transaction is completed. The following illustrates a typical Hibernate session:

Session session = null; UserInfo user = null; Transaction tx = null; try { session = factory.openSession(); tx = session.beginTransaction(); user = (UserInfo)session.load(UserInfo.class, id); tx.commit(); } catch(Exception e) { if (tx != null) { try { tx.rollback(); } catch (HibernateException e1) { throw new DAOException(e1.toString()); } } throw new DAOException(e.toString()); } finally { if (session != null) { try { session.close(); } catch (HibernateException e) { } } }

The Hibernate Query Language
Hibernate offers a query language that embodies a very powerful and flexible mechanism to query, store, update, and retrieve objects from a database. This language, the Hibernate Query Language (HQL), is an object-oriented extension to SQL. HQL allows access to data in a variety of ways including object-oriented queries, as in the find() method of the Session object illustrated by the following example:

List users = session.find("from UserInfo as u where u.fullName = ?", "John Doe", Hibernate.STRING );

You can construct dynamic queries using Hibernate's criteria query API:

Criteria criteria = session.createCriteria(UserInfo.class); criteria.add(Expression.eq("fullName", "John Doe")); criteria.setMaxResults(20); List users = criteria.list();

If you prefer to use native SQL, you may express a query in SQL, using createSQLQuery():

List users = session.createSQLQuery("SELECT {user.*} FROM USERS AS {user}", "user", UserInfo.class).list();

Large numbers of objects returned from a query will be loaded as needed when one of the iterate() methods is used. The iterate() methods typically offer better performance since they load objects on demand:

Iterator iter = session.iterate("from UserInfo as u where u.city = New York"); while (iter.hasNext()) { UserInfo user = (UserInfo)iter.next(); // process the user object here }

Thanks for your registration, follow us on our social networks to keep up-to-date