01: //$Id: DatasourceConnectionProvider.java 10075 2006-07-01 12:50:34Z epbernard $
02: package org.hibernate.connection;
03:
04: import java.sql.Connection;
05: import java.sql.SQLException;
06: import java.util.Properties;
07:
08: import javax.sql.DataSource;
09:
10: import org.hibernate.HibernateException;
11: import org.hibernate.cfg.Environment;
12: import org.hibernate.util.NamingHelper;
13:
14: import org.apache.commons.logging.Log;
15: import org.apache.commons.logging.LogFactory;
16:
17: /**
18: * A connection provider that uses a <tt>DataSource</tt> registered with JNDI.
19: * Hibernate will use this <tt>ConnectionProvider</tt> by default if the
20: * property <tt>hibernate.connection.datasource</tt> is set.
21: * @see ConnectionProvider
22: * @author Gavin King
23: */
24: public class DatasourceConnectionProvider implements ConnectionProvider {
25: private DataSource ds;
26: private String user;
27: private String pass;
28:
29: private static final Log log = LogFactory
30: .getLog(DatasourceConnectionProvider.class);
31:
32: public DataSource getDataSource() {
33: return ds;
34: }
35:
36: public void setDataSource(DataSource ds) {
37: this .ds = ds;
38: }
39:
40: public void configure(Properties props) throws HibernateException {
41:
42: String jndiName = props.getProperty(Environment.DATASOURCE);
43: if (jndiName == null) {
44: String msg = "datasource JNDI name was not specified by property "
45: + Environment.DATASOURCE;
46: log.fatal(msg);
47: throw new HibernateException(msg);
48: }
49:
50: user = props.getProperty(Environment.USER);
51: pass = props.getProperty(Environment.PASS);
52:
53: try {
54: ds = (DataSource) NamingHelper.getInitialContext(props)
55: .lookup(jndiName);
56: } catch (Exception e) {
57: log.fatal("Could not find datasource: " + jndiName, e);
58: throw new HibernateException("Could not find datasource", e);
59: }
60: if (ds == null) {
61: throw new HibernateException("Could not find datasource: "
62: + jndiName);
63: }
64: log.info("Using datasource: " + jndiName);
65: }
66:
67: public Connection getConnection() throws SQLException {
68: if (user != null || pass != null) {
69: return ds.getConnection(user, pass);
70: } else {
71: return ds.getConnection();
72: }
73: }
74:
75: public void closeConnection(Connection conn) throws SQLException {
76: conn.close();
77: }
78:
79: public void close() {
80: }
81:
82: /**
83: * @see ConnectionProvider#supportsAggressiveRelease()
84: */
85: public boolean supportsAggressiveRelease() {
86: return true;
87: }
88:
89: }
|