summaryrefslogtreecommitdiff
path: root/orkbasej/java/net/sf/oreka/srvc/ObjectServiceHbn.java
blob: 06a627472b780769f46e233a11ee55c9d467823a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package net.sf.oreka.srvc;

import net.sf.oreka.HibernateManager;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class ObjectServiceHbn implements ObjectService {

	static Logger logger = Logger.getLogger(ObjectServiceHbn.class);	
	
	public Object getObjectById(java.lang.Class cl, int id) {
		
		Session hbnSession = null;
		Object obj = null;
		
		logger.debug("Retrieving " + cl.getName() +  " object with id:" + id);
		
		try
		{
			hbnSession = HibernateManager.instance().getSession();
			obj = hbnSession.get(cl, id);
		}
		catch ( HibernateException he ) {
			logger.error("getObjectById: exception:" + he.getClass().getName());
		}
		catch (Exception e)
		{
			logger.error("getObjectById: exception:", e);
		}
		finally {
			if(hbnSession != null) {hbnSession.close();}
		}
		return obj;
	}

	public void saveObject(Object obj) {
		
		Session hbnSession = null;
		Transaction tx = null;
		
		logger.debug("Saving " + obj.getClass().getName());
		
		try
		{
			hbnSession = HibernateManager.instance().getSession();
			tx = hbnSession.beginTransaction();
			hbnSession.saveOrUpdate(obj);	// was merge
			tx.commit();
		}
		catch ( HibernateException he ) {
			logger.log(Level.ERROR, he.toString());
			he.printStackTrace();
		}
		catch (Exception e)
		{
			logger.error(e);
			e.printStackTrace();
		}
		finally {
			if(hbnSession != null) {hbnSession.close();}
		}
	}
	
	public int getNumObjects(java.lang.Class cl) {
		
		Session hbnSession = null;
		int numObjets = 0;
		
		try
		{
			hbnSession = HibernateManager.instance().getSession();

			Criteria crit = hbnSession.createCriteria(cl);
			
			// figure out total number of objects returned
			ScrollableResults scrollRes = crit.scroll();
			if ( scrollRes.last() ) {
				numObjets = scrollRes.getRowNumber();
			}
		}
		catch ( HibernateException he ) {
			logger.error("getNumObjects: exception:" + he.getClass().getName());
		}
		catch (Exception e)
		{
			logger.error("getNumObjects: exception:", e);
		}
		finally {
			if(hbnSession != null) {hbnSession.close();}
		}
		
		return numObjets;
	}
}