Java Reference
In-Depth Information
import sample.AdException;
import sample.entity.Advert;
import sample.entity.User;
public class AdvertDAO extends DAO {
public Advert create(String title, String message, User user)
throws AdException {
try {
begin();
Advert advert = new Advert(title, message, user);
getSession().save(advert);
commit();
return advert;
} catch (HibernateException e) {
rollback();
throw new AdException("Could not create advert", e);
}
}
public void delete(Advert advert)
throws AdException
{
try {
begin();
getSession().delete(advert);
commit();
} catch (HibernateException e) {
rollback();
throw new AdException("Could not delete advert", e);
}
}
}
If you compare the amount of code required to create our DAO classes here with the
amount of code that would be required to implement them using the usual JDBC approach,
you will see that Hibernate's logic is admirably compact.
The Example Client
Listing 3-23 shows the example code tying this together. Of course, this isn't a full application,
but you now have all the DAOs necessary to manage the advertisement database. This exam-
ple gives a flavor of how they can be used.
The code should be run with the tasks in the Ant script delivered in Listing 3-1. After run-
ning the
exportDDL
task to create the empty database, you should run the
createUsers
and
createCategories
tasks to provide initial users and categories, and then the
postAdverts
task to
place advertisements in the database. Finally, run the
listAdverts
task to display the saved data.
The code invoking the DAOs to perform the tasks in question is shown in Listing 3-23.
Search WWH ::
Custom Search