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 import uk.co.concise.maven.hdc.model.Label;
12
13
14 /***
15 * Data accessor object for labels.
16 * @author martenssonb
17 */
18 public class LabelDao {
19
20 /***
21 * Persists a label or updates if it was already persisted.
22 * @param label label to be persisted.
23 */
24 public void saveOrUpdateLabel(Label label) {
25 Session session = HibernateUtil.currentSession();
26 Transaction tx = null;
27 try {
28 tx = session.beginTransaction();
29
30 session.saveOrUpdate(label);
31 tx.commit();
32 } catch (HibernateException e) {
33 HibernateUtil.handleHibernateException(tx, e);
34 } finally {
35 HibernateUtil.closeSession();
36 }
37 }
38
39 /***
40 * Returns a label. Returns null if
41 * no label was found.
42 * @param chart the chart that the label belongs to.
43 * @param text the text that makes up the label.
44 * @return a label for a certain chart with a certain text.
45 */
46 public Label findByChartAndText(Chart chart, String text) {
47 Session session = HibernateUtil.currentSession();
48 Transaction tx = null;
49 Label label = null;
50 try {
51 tx = session.beginTransaction();
52
53 Query q = session.createQuery("from Label as label "
54 + "where label.chart = :chart and label.text = :text");
55 q.setEntity("chart", chart);
56 q.setString("text", text);
57
58 Iterator chartIter = q.iterate();
59 if (chartIter.hasNext()) {
60 label = (Label) chartIter.next();
61 }
62 tx.commit();
63 } catch (HibernateException e) {
64 HibernateUtil.handleHibernateException(tx, e);
65 } finally {
66 HibernateUtil.closeSession();
67 }
68 return label;
69 }
70
71 /***
72 * Returns all labels for a chart.
73 * @param chart the chart to return labels for.
74 * @return all labels for a chart.
75 */
76 public List findByChart(Chart chart) {
77 Session session = HibernateUtil.currentSession();
78 Transaction tx = null;
79 List labels = null;
80 try {
81 tx = session.beginTransaction();
82
83 Query q = session.createQuery("from Label as label "
84 + "where label.chart = :chart");
85 q.setEntity("chart", chart);
86
87 labels = q.list();
88 tx.commit();
89 } catch (HibernateException e) {
90 HibernateUtil.handleHibernateException(tx, e);
91 } finally {
92 HibernateUtil.closeSession();
93 }
94 return labels;
95 }
96
97 }