01: package simpleorm.simplewebapp.eg.hibernatetest;
02:
03: import org.hibernate.SessionFactory;
04: import org.hibernate.Session;
05: import org.hibernate.criterion.Expression;
06: import org.hibernate.cfg.Configuration;
07: import simpleorm.simplewebapp.eg.simple.WTestDatabase;
08: import simpleorm.simplewebapp.eg.simple.WTestRecord;
09: import simpleorm.simplewebapp.eg.WAllTests;
10:
11: import java.util.List;
12: import java.util.Iterator;
13:
14: public class WHibernateMain extends WTestDatabase {
15:
16: private static SessionFactory sessionFactory;
17:
18: public @Override
19: String getDatabaseName() {
20: return "Hibernate/HSQL";
21: }
22:
23: /** Set test system to use Hibernate instead of MockDB.
24: * Called once by WInitPage. */
25: public static void setHibernate() {
26: sessionFactory = new Configuration().configure()
27: .buildSessionFactory();
28: WTestDatabase.db = new WHibernateMain();
29: db.beginTransaction();
30: db.addTestRows();
31: db.endTransaction();
32: }
33:
34: public static void main(String[] argv) throws Exception {
35: setHibernate();
36:
37: // connection info in hibernate.cfg.xml file at top of test folder.
38:
39: db.beginTransaction();
40:
41: Iterator<WTestRecord> it = db.getIterator(null, null);
42: while (it.hasNext()) {
43: WTestRecord tr = it.next();
44: System.out.println("\n==== TestRecord: " + tr.getId()
45: + " Name " + tr.getName());
46: }
47:
48: WTestRecord tr3 = db.findRow("three");
49: WAllTests.assertEquals("Third one row", tr3.getName());
50:
51: db.removeRow("three");
52:
53: db.endTransaction();
54: }
55:
56: public void beginTransaction() {
57: Session session = sessionFactory.getCurrentSession();
58: session.beginTransaction();
59: }
60:
61: public void endTransaction() {
62: Session session = sessionFactory.getCurrentSession();
63: session.getTransaction().commit();
64: }
65:
66: public WTestRecord addRow(String id) {
67: Session session = sessionFactory.getCurrentSession();
68: WTestRecord tr = new WTestRecord(0, id);
69: session.save(tr);
70: return tr;
71: }
72:
73: public WTestRecord findRow(String id) {
74: Session session = sessionFactory.getCurrentSession();
75: WTestRecord row = (WTestRecord) session.createCriteria(
76: WTestRecord.class).add(Expression.eq("idx", id))
77: .uniqueResult();
78: return row;
79: }
80:
81: public void removeRow(String id) {
82: Session session = sessionFactory.getCurrentSession();
83: WTestRecord row = findRow(id);
84: session.delete(row);
85: }
86:
87: public Iterator<WTestRecord> getIterator(String nameWord,
88: String sorter) {
89: Session session = sessionFactory.getCurrentSession();
90: List results = session.createQuery("from WTestRecord").list();
91: return results.iterator();
92: }
93:
94: }
|