View Javadoc

1   package uk.co.concise.maven.hdc.dao;
2   
3   import java.util.Iterator;
4   import java.util.List;
5   
6   import net.sf.hibernate.HibernateException;
7   import net.sf.hibernate.Query;
8   import net.sf.hibernate.Session;
9   import net.sf.hibernate.Transaction;
10  import uk.co.concise.maven.hdc.model.Chart;
11  
12  
13  /***
14   * Data accessor object for charts.
15   * @author martenssonb
16   */
17  public class ChartDao {
18  
19      /***
20       * Persists a chart.
21       * @param chart chart to be persisted.
22       */
23      public void saveOrUpdateChart(Chart chart) {
24          Session session = HibernateUtil.currentSession();
25          Transaction tx = null;
26          try {
27              tx = session.beginTransaction();
28  
29              session.saveOrUpdate(chart);
30              tx.commit();
31          } catch (HibernateException e) {
32              HibernateUtil.handleHibernateException(tx, e);
33          } finally {
34              HibernateUtil.closeSession();
35          }
36      }
37      
38      /***
39       * Returns a chart with a certain heading. Returns null if
40       * no chart was found.
41       * @param heading the heading of the chart to be returned.
42       * @return a chart with a certain heading.
43       */
44      public Chart findByHeading(String heading) {
45          Session session = HibernateUtil.currentSession();
46          Transaction tx = null;
47          Chart chart = null;
48          try {
49              tx = session.beginTransaction();
50  
51              Query q = session.createQuery("from Chart as chart "
52                      + "where chart.heading = :heading");
53              q.setString("heading", heading);
54              Iterator chartIter = q.iterate();
55              if (chartIter.hasNext()) {
56                  chart = (Chart) chartIter.next();
57              }
58              tx.commit();
59          } catch (HibernateException e) {
60              HibernateUtil.handleHibernateException(tx, e);
61          } finally {
62              HibernateUtil.closeSession();
63          }
64          return chart;
65      }
66  
67      /***
68       * Returns all charts.
69       * @return all charts.
70       */
71      public List findAll() {
72          Session session = HibernateUtil.currentSession();
73          Transaction tx = null;
74          List charts = null;
75          try {
76              tx = session.beginTransaction();
77              charts = session.find("from Chart");
78              tx.commit();
79              return charts;
80          } catch (HibernateException e) {
81              HibernateUtil.handleHibernateException(tx, e);
82          } finally {
83              HibernateUtil.closeSession();
84          }
85          return charts;
86      }
87  
88  }