Hi,
I'm using Hibernate 4.0.1.Final and MySql 5.1. Right now, my DAOs are implementations of interfaces I set up. I do this because occassionally during testing I can substitute different mock implementations of those DAOs. However, I'm duplicating code (getting sessions and session factories) and I was wondering how I can design my application more elegantly. For example, in one of my DAOs I have ...
Code:
public class EventFeedsDaoImpl implements EventFeedsDao {
private static SessionFactory sessionFactory = null;
private static final Logger LOG = Logger.getLogger(EventFeedsDaoImpl.class);
public EventFeedsDaoImpl() {
final Configuration configuration = new Configuration();
configuration.configure();
final ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} // EventFeedsDaoImpl
@Override
public Set<EventFeed> getAllEventFeeds() {
final Session session = this.getSession();
final Set<EventFeed> eventFeeds = new HashSet<EventFeed>();
try {
final Criteria crit = session.createCriteria(EventFeed.class);
final List results = crit.list();
if (results != null && results.size() > 0) {
eventFeeds.addAll( results );
} // if
session.flush();
} catch (HibernateException e) {
LOG.error(e.getMessage(), e);
} finally {
if (session != null) {
try {
session.close();
} catch (HibernateException e) {
e.printStackTrace();
}
}
} // try
return eventFeeds;
}
private Session getSession() {
Session session = null;
try {
session = sessionFactory.openSession();
} catch (HibernateException e) {
e.printStackTrace();
}
return session;
}
}
Note that I have the "getSession" method in all my DAO implementations, in addition to the same session factory initialization code. What is a better way to go?
Thanks, - Dave