Java Reference
In-Depth Information
Listing 3-17. Retrieving a User Object from the Database
try {
begin();
Query q = getSession().createQuery("from User where name = :username");
q.setString("username",username);
User user = (User)q.uniqueResult();
commit();
return user;
} catch( HibernateException e ) {
rollback();
throw new AdException("Could not get user " + username,e);
}
We begin a transaction, create a Query object (similar in purpose to PreparedStatement in
connected applications), populate the parameter of the query with the appropriate username,
and then list the results of the query. We extract the user (if one has been retrieved success-
fully) and commit the transaction. If there is a problem reading the data, the transaction will
be rolled back.
The key line used to obtain the User entity is:
User user = (User)q.uniqueResult();
We use the uniqueResult() method because it is guaranteed to throw an exception if some-
how our query identifies more than one User object for the given username. In principle, this
could happen if the underlying database's constraints don't match our mapping constraint for
a unique username field, and an exception is an appropriate way to handle the failure.
The logic to delete a user from the database (Listing 3-18) is even more trivial than that
required to create one.
Listing 3-18. Deleting a User Object and Reflecting This in the Database
try {
begin();
getSession().delete(user);
commit();
} catch( HibernateException e ) {
rollback();
throw new AdException("Could not delete user " + user.getName(),e);
}
We simply instruct the session to delete the User object from the database, and commit
the transaction. The transaction will roll back if there is a problem—for example, if the user
has already been deleted.
You have now seen all the basic operations that we want to perform on our data, so we
will now take a look at the architecture we are going to use to do this.
Search WWH ::




Custom Search