Revision 11:45993ab31d47

View differences:

pom.xml
247 247

  
248 248
	<dependencies>
249 249
		<dependency>
250
			<groupId>net.penril.commons</groupId>
251
			<artifactId>commons-hibernate-util</artifactId>
252
			<version>0.0.1-SNAPSHOT</version>
253
		</dependency>
250
 			<groupId>org.hibernate</groupId>
251
 			<artifactId>hibernate-core</artifactId>
252
 			<version>3.3.1.GA</version>
253
 			<type>jar</type>
254
 			<scope>compile</scope>
255
 		</dependency>
254 256
		<dependency>
255 257
			<groupId>junit</groupId>
256 258
			<artifactId>junit</artifactId>
src/main/java/net/penril/generic/hibernate/GenericDAO.java
1
/**
2
 * Copyright (M) 2009 Penril Datability (M) Sdn Bhd All rights reserved.
3
 *
4
 * This software is copyrighted. Under the copyright laws, this software
5
 * may not be copied, in whole or in part, without prior written consent
6
 * of Penril Datability (M) Sdn Bhd or its assignees. This software is
7
 * provided under the terms of a license between Penril Datability (M)
8
 * Sdn Bhd and the recipient, and its use is subject to the terms of that
9
 * license.
10
 */
11
package net.penril.generic.hibernate;
12

  
13
import java.io.Serializable;
14
import java.util.List;
15

  
16
/**
17
 * PROGRAMMER: Danniell
18
 * CHANGE-NO:
19
 * TASK-NO:
20
 * DATE CREATED: Oct 27, 2010
21
 * TAG AS:
22
 * REASON(S):
23
 * MODIFICATION:
24
 */
25

  
26
/**
27
 * Represents Base Data Access Object
28
 */
29
public interface GenericDAO
30
{
31
	Object findById(Serializable id, boolean lock) throws Exception;
32
	
33
	List findAll()throws Exception;
34
	
35
	List findByExample(Object exampleInstance, String[] excludeProperty)throws Exception;
36
	
37
	Object makePersistent(Object entity)throws Exception;
38
	
39
	void makeTransient(Object entity)throws Exception;
40
	
41
	void flush()throws Exception;
42
	
43
	void clear()throws Exception;
44
	
45
	long getNextSequenceNumber(String sequenceName) throws Exception;
46
	
47
	long getCurrentSequenceNumber(String sequenceName) throws Exception;
48
}
src/main/java/net/penril/generic/hibernate/GenericDAOHibernate.java
1
/**
2
 * Copyright (M) 2009 Penril Datability (M) Sdn Bhd All rights reserved.
3
 *
4
 * This software is copyrighted. Under the copyright laws, this software
5
 * may not be copied, in whole or in part, without prior written consent
6
 * of Penril Datability (M) Sdn Bhd or its assignees. This software is
7
 * provided under the terms of a license between Penril Datability (M)
8
 * Sdn Bhd and the recipient, and its use is subject to the terms of that
9
 * license.
10
 */
11
package net.penril.generic.hibernate;
12

  
13
import java.io.Serializable;
14
import java.lang.reflect.ParameterizedType;
15
import java.math.BigDecimal;
16
import java.sql.CallableStatement;
17
import java.sql.Connection;
18
import java.sql.DatabaseMetaData;
19
import java.sql.SQLException;
20
import java.util.List;
21

  
22
import org.hibernate.Criteria;
23
import org.hibernate.LockMode;
24
import org.hibernate.Session;
25
import org.hibernate.Transaction;
26
import org.hibernate.criterion.Criterion;
27
import org.hibernate.criterion.Example;
28

  
29
public abstract class GenericDAOHibernate implements GenericDAO 
30
{
31
	private Class persistentClass;
32
	private Session session;
33
	
34
	public GenericDAOHibernate() 
35
	{
36
		this.persistentClass = (Class)((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
37
	}
38
	
39
	public void setSession(Session s) 
40
	{
41
		this.session = s;
42
	}
43
	
44
	/**
45
	 * 
46
	 * Will override the current session
47
	 *
48
	 * @param hibernateCfgPath The Hibernate configuration file path
49
	 */
50
	public void setSession(String hibernateCfgPath) 
51
	{
52
		HibernateUtils.overrideSession (hibernateCfgPath);
53
		this.session = HibernateUtils.currentSession ();
54
	}
55
	
56
	protected Session getSession() throws Exception 
57
	{
58
		if (session == null || session.isOpen () == false)
59
		{
60
			try
61
			{
62
				session = HibernateUtils.currentSession();
63
			}
64
			catch(Exception e)
65
			{
66
				throw e;
67
			}
68
		}
69
		return session;
70
	}
71
	
72
	public Class getPersistentClass() 
73
	{
74
		return persistentClass;
75
	}
76

  
77
	public void clear() throws Exception 
78
	{
79
		getSession ().clear ();
80
	}
81

  
82
	public List findAll() throws Exception 
83
	{
84
		return findByCriteria(null);
85
	}
86

  
87
	protected List findByCriteria (Criterion[] criterion) throws Exception
88
	{
89
		Criteria crit = getSession().createCriteria(getPersistentClass());
90
		if(criterion != null)
91
		{
92
			for(int i=0; i<criterion.length; i++){
93
				crit.add(criterion[0]);
94
			}
95
		}
96
		return crit.list();
97
	}
98

  
99
	public List findByExample(Object exampleInstance, String[] excludeProperty) throws Exception 
100
	{
101
		Criteria crit = getSession().createCriteria(getPersistentClass());
102
		Example example = Example.create(exampleInstance);
103
		
104
		for(int i=0; i<excludeProperty.length; i++){
105
			example.excludeProperty(excludeProperty[0]);
106
		}
107
		
108
		crit.add(example);
109
		return crit.list();
110
	}
111

  
112
	public Object findById(Serializable id, boolean lock) throws  Exception 
113
	{
114
		Object entity;
115
		if (lock)
116
		{
117
			entity = getSession().get(getPersistentClass(), id, LockMode.UPGRADE);
118
		}
119
		else
120
		{
121
			entity = getSession().get(getPersistentClass(), id);
122
		}
123
		return entity;
124
	}
125

  
126
	public void flush() throws  Exception 
127
	{
128
		getSession ().flush ();
129
	}
130

  
131
	public Object makePersistent(Object entity) throws  Exception 
132
	{
133
		getSession().saveOrUpdate(entity);
134
		return entity;
135
	}
136

  
137
	public void makeTransient(Object entity) throws  Exception 
138
	{
139
		getSession().delete(entity);
140
	}
141
	
142
	public long getNextSequenceNumber(String sequenceName) throws Exception {
143
		BigDecimal nextValue = new BigDecimal(0);
144

  
145
		// TODO: Don't forget to remove the following line!
146
		System.out.println("########## Retrieving next value for"
147
				+ " sequence: " + sequenceName);
148

  
149
		Session hSession = getSession();
150
		Transaction tx = null;
151
		try {
152
			Connection conn = hSession.connection();
153
			DatabaseMetaData metaData = conn.getMetaData();
154
			String jdbcUrl = metaData.getURL();
155
			if (jdbcUrl.startsWith("jdbc:oracle")) {
156
				nextValue = (BigDecimal) hSession.createSQLQuery(
157
						"select " + sequenceName + ".nextval from dual")
158
						.uniqueResult();
159

  
160
			} else if (jdbcUrl.startsWith("jdbc:sqlserver")) {
161
				// TODO: Don't forget to remove the following line!
162
				System.out
163
						.println("########## Simulating sequences in SQL Server.");
164
				
165
				tx = hSession.beginTransaction();
166
				CallableStatement cstmt = conn.prepareCall(//
167
						"{call nextval_" + sequenceName + "(?)}");
168
				cstmt.registerOutParameter(1, java.sql.Types.BIGINT);
169
				cstmt.execute();
170
				nextValue = cstmt.getBigDecimal(1);
171
				tx.commit();
172

  
173
			} else
174
				throw new RuntimeException(
175
						"The jdbc driver is not in supported.");
176

  
177
		} catch (SQLException e) {
178
			if (tx != null && tx.isActive())
179
				tx.rollback();
180
			throw new RuntimeException(e);
181

  
182
		} finally {
183
			hSession.close();
184
		}
185
		long longValue = nextValue.longValue();
186
		// TODO: Don't forget to remove the following line!
187
		System.out.println("########## Last sequence value: " + longValue);
188
		return longValue;
189
	}
190

  
191
	public long getCurrentSequenceNumber(String sequenceName) throws Exception {
192
		BigDecimal currentValue = new BigDecimal(0);
193

  
194
		// TODO: Don't forget to remove the following line!
195
		System.out.println("########## Retrieving current value for"
196
				+ " sequence: " + sequenceName);
197
		try {
198
			Connection conn = getSession().connection();
199
			DatabaseMetaData metaData = conn.getMetaData();
200
			String jdbcUrl = metaData.getURL();
201
			if (jdbcUrl.startsWith("jdbc:oracle")) {
202
				currentValue = (BigDecimal) getSession().createSQLQuery(
203
						"select " + sequenceName + ".currval from dual")
204
						.uniqueResult();
205

  
206
			} else if (jdbcUrl.startsWith("jdbc:sqlserver")) {
207
				currentValue = (BigDecimal) getSession().createSQLQuery(
208
						"select seq_value from " + sequenceName).uniqueResult();
209
			} else
210
				throw new RuntimeException(
211
						"The jdbc driver is not in supported.");
212

  
213
		} catch (SQLException e) {
214
			throw new RuntimeException(e);
215

  
216
		} finally {
217
			getSession().close();
218
		}
219
		long longValue = currentValue.longValue();
220
		// TODO: Don't forget to remove the following line!
221
		System.out.println("########## Current sequence value: " + longValue);
222
		return longValue;
223
	}
224
}
src/main/java/net/penril/generic/hibernate/HibernateUtils.java
1
/**
2
 * Copyright (c) 2009 Penril Datability (SEA) Sdn Bhd All rights reserved.
3
 *
4
 * This software is copyrighted. Under the copyright laws, this software
5
 * may not be copied, in whole or in part, without prior written consent
6
 * of Penril Datability (SEA) Sdn Bhd or its assignees. This software is
7
 * provided under the terms of a license between Penril Datability (SEA)
8
 * Sdn Bhd and the recipient, and its use is subject to the terms of that
9
 * license.
10
 */
11

  
12
package net.penril.generic.hibernate;
13

  
14
import org.hibernate.HibernateException;
15
import org.hibernate.Session;
16
import org.hibernate.SessionFactory;
17
import org.hibernate.cfg.Configuration;
18

  
19
/**
20
 * Configures and provides access to Hibernate sessions, tied to the current
21
 * thread of execution. Follows the Thread Local Session pattern, see {@link http://hibernate.org/42.html}.
22
 * 
23
 * <pre>
24
 *  For this project, all the hibernate configuration file must be at the "/com/ib/ibss/hibernate/configuration/hibernate.cfg.xml".
25
 *  It is hard coded. Just make sure out the hibernate configuration file at the mentioned path.
26
 * </pre>
27
 */
28
public class HibernateUtils {
29

  
30
	private static final Object CONFIG_LOCK = new Object();
31

  
32
	/**
33
	 * <pre>
34
	 * Location of hibernate.cfg.xml file. NOTICE: Location should be on the
35
	 * classpath as Hibernate uses #resourceAsStream style lookup for its
36
	 * configuration file. That is place the config file in a Java package - the
37
	 * default location is the default Java package.
38
	 * 
39
	 * Examples:
40
	 * <code>CONFIG_FILE_LOCATION = "/hibernate.conf.xml". 
41
	 * CONFIG_FILE_LOCATION = "/com/foo/bar/myhiberstuff.conf.xml".</code>
42
	 * 
43
	 * For this project, all the hibernate configuration file must be at the "/com/ib/ibss/hibernate/configuration/hibernate.cfg.xml".
44
	 * It is hard coded. Just make sure out the hibernate configuration file at the mentioned path.
45
	 * </pre>
46
	 */
47
	private static String CONFIG_FILE_LOCATION = "/com/ib/hibernate/configuration/hibernate.cfg.xml";
48
	private static Configuration cfg = null;
49
	private static SessionFactory sessionFactory = null;
50
	private static ThreadLocal session = null;
51

  
52
	/**
53
	 * To create a new session
54
	 */
55
	private static void init() {
56
		synchronized (CONFIG_LOCK) {
57
			if (session == null) {
58
				/** The single instance of hibernate configuration */
59
				cfg = new Configuration();
60

  
61
				/** The single instance of hibernate SessionFactory */
62
				sessionFactory = cfg.configure(CONFIG_FILE_LOCATION).buildSessionFactory();
63

  
64
				/** Holds a single instance of Session */
65
				session = new ThreadLocal();
66
			}
67
		}
68
	}
69

  
70
	/**
71
	 * 
72
	 * Override the current session if already exist. If not, create a new session.
73
	 * 
74
	 * @param p
75
	 */
76
	public static void overrideSession(String p) {
77
		synchronized (CONFIG_LOCK) {
78
			/** The single instance of hibernate configuration */
79
			cfg = new Configuration();
80

  
81
			/** The single instance of hibernate SessionFactory */
82
			sessionFactory = cfg.configure(p).buildSessionFactory();
83

  
84
			/** Holds a single instance of Session */
85
			session = new ThreadLocal();
86
		}
87
	}
88

  
89
	/**
90
	 * Returns the ThreadLocal Session instance. Lazy initialize the <code>SessionFactory</code> if needed.
91
	 * Will instantiate the hibernate session if not exist.
92
	 * 
93
	 * @return Session The hirbernate session.
94
	 * @throws HibernateException
95
	 */
96
	public static Session currentSession() throws HibernateException {
97
		init();
98
		Session m_oSession = (Session) session.get();
99
		// Open a new Session, if this Thread has none yet
100
		if (m_oSession == null || (m_oSession != null && !m_oSession.isConnected())) {
101
			try {
102
				m_oSession = sessionFactory.openSession();
103
				session.set(m_oSession);
104

  
105
			} catch (Throwable ex) {
106
				// Make sure you log the exception, as it might be swallowed
107
				throw new ExceptionInInitializerError(ex);
108
			}
109
		}
110
		return m_oSession;
111
	}
112

  
113
	/**
114
	 * Close the single hibernate session instance.
115
	 * 
116
	 * @throws HibernateException
117
	 */
118
	public static void closeSession() throws HibernateException {
119
		Session m_oSession = (Session) session.get();
120
		session.set(null);
121
		if (m_oSession != null) {
122
			m_oSession.close();
123
		}
124
	}
125
}

Also available in: Unified diff