Hibernate « Database JDBC « Java Articles

Home
Java Articles
1.Build Deploy
2.Class
3.Core Library
4.Data Types
5.Database JDBC
6.Design
7.Development
8.File Input Output
9.Graphics Desktop
10.J2EE Enterprise
11.J2ME Wireless
12.JVM
13.Language
14.Library Product
15.Network
16.Security
17.SOA Web Services
18.Test
19.Web Development
20.XML
Java Articles » Database JDBC » Hibernate 
Object-relational mapping in Java is a tricky business, and solutions like JDBC and entity beans have met with less than overwhelming enthusiasm. But a new generation of ORM solutions has since emerged. These tools allow for easier programming and a closer adherence to the ideals of object-oriented programming and multi-tiered architectural development. Learn how Hibernate, iBATIS, and the Java Persistence API compare based on factors such as query-language support, performance, and portability across different relational databases.

Many Web applications exist to provide access to copious amounts of data stored in a relational database, but what's the easiest way to enable users to search through that data and find what they need? In this article, Dr. Xinyu Liu introduces Hibernate Search, which integrates the sophisticated search capabilities of Lucene with the familiar object-relational mapping framework of Hibernate.

Max Ross is the Google engineer who spends his days working on the Google App Engine data store. On the side he works on Hibernate Shards, another scalability-obsessed project that is open source. In this talk with Andrew Glover, Max explains sharding, which is the strategy of storing application data on multiple databases. As Max explains, sharding may not be popular but it is a necessary for some applications dealing with a high volume of data. In those cases, Hibernate Shards provides a unified view into any number of databases, making huge amounts of data manageable even as the system evolves.

Instances of the Message class may be managed (made persistent) by Hibernate, but they don't have to be. Since the Message object doesn't implement any Hibernate-specific classes or interfaces, we can use it like any other Java class:

Once you have decided that it is OK to use your existing Hibernate objects outside of your container, then the first thing you'll have to do is to manage all of the configuration yourself. The approach I will take for the rest of the article is via a command line, standalone Java app. Since you probably already have a Hibernate XML configuration file set up, you already know what parameters are required, such as JNDI DataSource name, entity mapping files, and miscellaneous properties for logging SQL. If you decide to use a command-line application, you will have to figure out how to parse the XML file and add it to your new configuration. While parsing an XML document is not impossible, it can sometimes be a little side project in itself. Thus, I recommend using a regular properties file. A properties file is pretty straightforward and fairly easy to load up and get values from. The following is an example of a minimal set of properties needed to configure Hibernate (sans any entity mappings):

Hibernate will help us to painlessly store the data in permanent storage without too much hassle about choosing the kind of storage, installation, or configuration. Hibernate allows us to store any kind of objects; therefore, our application does not need to know that its data will be persisted using Hibernate. Of course, everything mentioned here can be applied in the opposite direction: fetching already prepared objects from a storage is now nearly trivial. Updating and deleting data is also available.

Hibernate annotations also support the new EJB 3 persistence specifications. These specifications aim at providing a standardized Java persistence mechanism. While Hibernate 3 also provides a few extensions, you can quite easily stick to the standards and code your Hibernate persistence layer using the EJB 3 programming model.

Java Data Objects (JDO) is an interface-based standard for persistence or, as Tate and Gehtland say, "the non-EJB standard for persistence in Java applications." Setting aside the controversies that once swirled over JDO, they look at how to bring a top implementation, Kodo, to bear on your Spring application. They then move on to the most popular of the OR frameworks, and perhaps the best integrated with Spring: Hibernate. As they point out, "though it's nonstandard, you could say that behind EJB, Hibernate is the most popular persistence framework in the world." This chapter not only helps you with the nuts and bolts of setting up each framework, but also clearly shows how different their approaches are.

This article is intended to show how Spring can be used to assemble components, including their transaction contexts. Connecting to a single data store from within a J2EE application is not a big hurdle. But when it comes to assembly and integration of enterprise-class components, the scenario gets complicated. A single component would be backed up by a single data store or a number of data stores. So, when we speak of assembling two or more components, we are expected to maintain the atomicity of operations done in many data stores, across components. A J2EE server provides a container for these components so that the container is able to take care of transactional atomicity and isolation across components, too. When we are not using a J2EE server, Spring helps us. Spring is based on Inversion of Control (also called Dependency Injection) for wiring not only the component services together, but also their associated transaction contexts. For the purpose of this article, we are using Hibernate as an object/relational persistence and query service.

Enterprise Java applications often move data back and forth between Java objects and relational databases. There are several ways to do this, ranging from manually coded SQL to sophisticated object-relational mapping (ORM) solutions such as Hibernate. Regardless of what technique you use, once you start persisting Java objects to a database object identity becomes a complex and difficult-to-manage topic. The possibility arises that you will instantiate two different objects that represent the same row in the database. To handle this, you must properly implement the equals() and hashCode() methods on your persistent objects, but a proper implementation of these methods may be trickier than it at first appears. To make matters worse, the conventional wisdom (as espoused in the official Hibernate documentation) may not lead you to the most practical solution for new projects.

This process is illustrated in Figure 1. First, you take the set of Hibernate mapping files. You may also need a hbm2java configuration file, generally called hbm2java.xml. Using these two entries, the hbm2java tool generates one or more Java classes for each Hibernate mapping file. The hbm2java configuration file can be useful for fine-tuning the class-generation process. (In Hibernate 3, this file is no longer used.)

Hibernate 2.x provides basic table-to-object mapping, normal association mapping (including one-to-one, one-to-many, and many-to-many relationships), polymorphism mapping, etc. Hibernate 3.x pushes this to another level by enhancing mapping flexibility with formula, filter, subselect, etc., which provide fine-grained interpretation features.

Hibernate delivers a high-performance, open source persistence framework that can greatly reduce the amount of time and effort needed to code, test, and deploy applications. The introductory article shows you how to create, update, retrieve and delete persistent classes, and how to persist object collections using Hibernate. Source code and mapping documents for an example application have been provided.

This experience has led directly to the design and development of Naked Objects version 3. Our aim for version 3 is to allow users to gain all of the advantages that the DSFA has already demonstrated at the business programming level, whilst avoiding almost all of the technical integration work needed for version 2. This is being achieved both by extending the fundamental capabilities of the framework, and by making it interwork with open source solutions that have already solved other parts of the puzzle such as Hibernate. We have also taken the opportunity to introduce other changes that will extend both the richness and the applicability of the Naked Objects approach.

Hibernate in Action is both an introduction to the theoretical aspects of automated object/relational mapping and a practical guide to the use of Hibernate. The extensive example code implements an online auction application.

This excerpt, "Criteria Queries," from James Elliot's Hibernate: A Developer's Notebook, shows you how to use simple criteria, compound criteria, apply criteria to associations, and query by example using Hibernate.

We've seen a few people using internationalized reference data where labels displayed in the user interface depend upon the user's language. It's not immediately obvious how to deal with this in Hibernate, and I've been meaning to write up my preferred solution for a while now.

Hibernate3 adds the ability to pre-define filter criteria and attach those filters at both a class and a collection level. What's a "pre-defined filter criteria"? Well, it's the ability to define a limit clause very similiar to the existing "where" attribute available on the class and various collection elements. Except these filter conditions can be parameterized! The application can then make the decision at runtime whether given filters should be enabled and what their parameter values should be.

Anyway a few days ago The Server Side (TSS) posted an article (discussion thread here) about a new (to me that is) ORM mapping tool called Cayenne. I was intrigued so I downloaded a copy and started making the following object graph persistable (I also blogged about my expierence testing the Hibernate mappings with DBUnit here a couple of weeks ago.).

The solution is to use an object generator, a modified data access object (DAO) that retrieves and assigns identifiers during object creation. Think of it as an object factory designed for Hibernate. Each object returned from the generator has a database-generated identifier that's guaranteed to be stable and unique. The key difference between this and the classic approach is that this all happens before the object is persisted.

If you have a large J2EE project?possibly in production?is migrating your existing homegrown or entity-bean-based solution worth it? Perhaps, it all depends on whether your existing persistence layer is deficient or unable to scale to meet your long-term goals. In some cases, the risk may be high and the costs outweigh the benefits. But if you've decided to go with Hibernate, you can minimize the impact of the change and make the transition?if not painless?at least well structured and predictable with a bit of upfront design.

Java EE 5 provides all the features and functions necessary to build a robust enterprise application right in the EJB 3.0 container, but you still can use the power, flexibility, and relative strengths of Spring and Hibernate to further improve the productivity and quality of your applications. This article demonstrates how to build a Java EE application that uses EJB 3.0, Spring 2.0, and Hibernate together. By implementing a component architecture, the application employs EJB 3.0 while using Spring 2.0 as a dependency-injection, AOP container and Hibernate as an ORM persistence provider.

Hibernate is a powerful, high performance object/relational persistence and query service. Hibernate lets you develop persistent classes following object-oriented idiom - including association, inheritance, polymorphism, composition, and collections. Hibernate allows you to express queries in its own portable SQL extension (HQL), as well as in native SQL, or with an object-oriented Criteria and Example API.

The traditional approach for a Hibernate developer to enable this sort of functionality generally involves building an HQL (Hibernate Query Language) query on the fly, based on the search criteria the user entered. Next, he or she uses this query string to create a Hibernate Query object and then sets the non-null parameter values. The code looks something like this:

Hibernate is a pure Java object-relational mapping and persistence framework that allows you to map plain old Java objects to relational database tables using XML configuration files. Using Hibernate can save a lot of development time on a project, since the whole JDBC layer is managed by the framework. This means that your application's data access layer will sit above Hibernate and be completely abstracted away from of the underlying data model.

Let's face it, if you're hand-coding SQL statements in your enterprise application, you are spending a significant amount of your development time updating and maintaining your persistence layer. Wouldn't it be nice if you could easily persist your existing JavaTM objects to a relational database like IBM® DB2® Universal DatabaseTM (UDB)?

Implementation of object-relational mapping (O/R mapping) is a general need for many projects in software development. Usually, work with the automation process of data storage is very boring, and at manual implementation there is a danger of mistakes and bugs. Also, to add constantly varying requirements, it is necessary for the developer to take into account the complex process of synchronization of all initial code and data storage structures. More than that, taking into account the necessity of portability of application between platforms, it all becomes even more complex and confusing.

The mapping documents are compiled at application start-up to provide Hibernate with information about the persistent objects' corresponding classes, their respective structures, to which database table should they be mapped, and how. Hibernate also uses these mapping documents to generate corresponding database schema and stub Java classes for the persistence layer, using inbuilt utilities called SchemaExport and CodeGenerator, respectively.

As a persistence service, Hibernate must work with multiple databases and within various application environments. Supporting these variations requires Hibernate to be highly configurable to adapt to different environments. After all, running a standalone application can be quite different from running a web application. Differences in obtaining database connections, for instance, can be significant. Hibernate is typically configured in two steps.

The most preferred way is using the Hibernate Query Language (HQL), which is an easy-to-learn and powerful query language, designed as a minimal object-oriented extension to SQL. HQL has syntax and keywords/clauses very similar to SQL. It also supports many other SQL-like features, such as aggregate functions (for example: sum(), max()) and clauses such as group by and order by clause.

My current project involves crunching a number of baseball statistics and running simulations with the data. Since the data was already in a relational database it was a chance for me to explore the Hibernate object-relational mapping system. I have been very impressed with Hibernate, but I ran into the problem was trying to insert a layer of indirection while using Hibernate as my data mapper for unit-testing. The extra layer was so flimsy that it felt embarrassing to write it. The real deployed version was simply a pass-through to a Hibernate-specific implementation. Even worse, the mock versions had more complexity in them than the real "production" version simply because they didn't have some of the basic object storage and mapping that came with Hibernate.

In the last few years, Hibernate has become one of the most popular Java open source frameworks available. However, developers don't always remember that the mapping files that drive Hibernate's behavior are as much a part of the program as the Java code. These files can contain defects, behave unexpectedly, and break when you change other parts of your system. In this article, I will show how you can use unit testing to assess the correctness of your Hibernate configuration. The article is a step-by-step approach that also explains some of the more common difficulties you may encounter while using Hibernate.

w___w__w.___j___av_a__2_s___.co__m__ | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.