An Introduction to Object-Relational Mapping with Hibernate

Finding and Loading Product Objects

Searching for and loading existing objects is a very simple task for Hibernate. With the use of its query language, we very easily can take an object (or set of objects) by its ID, a name, or other properties. We also can take either the whole object or its certain properties separately. Let's consider the FindProductByName class:

Initialize Hibernate as we did in the first example. This time, we already have created files of a configuration and mapping (XML file). The sess.find() method carries out the query and establishes the name of a product given to it, as an argument for the search with the Hibernate.STRING type.

As a result, we will get an object of the java.util.List class, filled with Product objects from a database that satisfies the search conditions.

With the Product p = (Product) list.get (0); expression, we take the first found object.

Updating and Removing Products

By now, you already should have a decent understanding of how Hibernate works. Therefore, now we will make our examples hardly less in size, having cleaned out all repeating and unimportant items.

Following is the example of how to increase all Products' prices by 10% in one transaction. We should write the following:

And, at last, for removal of a Product, we should cause a method sess.delete(product). Please, do not overlook also carrying out commit() at the end of transaction to confirm changes if only certainly the option autocommit in your database is turned on.

Afterword

This article shows what kind of tool is Hibernate, and also shows a few advantages. From it you have learned how simple is to keep any kind of Java objects, and then to manipulate them. Opportunities for Hibernate are incomparably wider. I also just need to mention that Hibernate arms the developer with very a powerful object-oriented query language, HQL, which has a set of various useful features.