Putting It All Together: Generating and Saving an Object
With the entire infrastructure in place, it's time to generate and save a simple User object. Notice how the interceptor is created and included in the session factory's configuration:
Configuration config = new Configuration();
Map<Long, User> users = new HashMap<Long, User>();
User user1 = null, user2 = null;
tx = session.beginTransaction();
UserDao userDao = new UserDao(session);
user1 = userDao.generate();
// Set properties...
user2 = userDao.generate();
// Set properties...
assert(users.size() == 2);
Note that the generated User objects are added to the collection before they're made persistent, but they still function properly afterwards. Generated objects are immediately usable in collections and don't require preparation or workarounds to make them work.
Object Generation: Developer's Cookbook
Adopting object generation in your projects is easy. In fact, it can be reduced to a series of simple steps:
- Create a new business object class that extends
AbstractGenericEntity and implements the
getEntityClass method. Remember, this class won't contain a property for the surrogate key (the ID) or implementations of either the
- Create a new DAO class that extends
AbstractGenericDao and implements the
getEntityClass method. The base class already provides typesafe implementations of the basic CRUD operations, but you may need additional methods to suit your needs.
- Write the descriptor for your business object as you would normally, but with one small change: use the
GeneratedIdentifierGenerator class as the generator and specify the object's real generator in the "delegate" parameter. Additional parameters can be specified and will be passed to the real generator when it's created.
- Use an instance of the
GeneratedEntityInterceptor class when creating the Hibernate configuration for the
SessionFactory used in your application. This ensures that the interceptor is incorporated and is used to minimize database traffic.
- Create all instances of the business object through its DAO. This is different than the approach you'll see elsewhere, where objects are created using the Java new operator and later handed to Hibernate. Object generation requires control over the creation process.
That's it. You've received the entire infrastructure for the generation approach to Hibernate persistence. However, you need to be aware of some limitations before deciding to integrate this approach into your project. Luckily, they're not showstoppers for the majority of modern enterprise applications.