Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Returns a database connection for the specified datasource
- * @param db - ex. "jdbc/DatasourceXyz"
- * @return db Connection
- * @throws Exception
- */
- public static Connection getDbConnection(String db) throws Exception {
- java.sql.Connection conn = null;
- try {
- LOG.debug("getting db connection for " + db + " ...");
- javax.naming.Context initCtx = new javax.naming.InitialContext();
- javax.naming.Context envCtx = (javax.naming.Context) initCtx.lookup("java:comp/env");
- javax.sql.DataSource ds = (javax.sql.DataSource) envCtx.lookup(db);
- conn = ds.getConnection();
- initCtx.close();
- LOG.debug("got db connection for " + db);
- LOG.debug("url = " + conn.getMetaData().getURL());
- } catch (Exception e) {
- String message = String.format("Exception thrown while creating a JDBC connection for %s: %s", db,
- e.getMessage());
- throw new Exception(message);
- }
- return conn;
- }
- <Context>
- <WatchedResource>WEB-INF/web.xml</WatchedResource>
- <WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>
- <!-- environment-specific jdbc data sources: -->
- <Resource name="jdbc/DatasourceXyz" auth="Container" type="javax.sql.DataSource" driverClassName="oracle.jdbc.OracleDriver" url="jdbc:oracle:thin:@hostname:1521:database" username="someUser" password="***" maxTotal="20" maxIdle="10" maxWaitMillis="60000"/>
- <!-- set other jdbc data sources below: -->
- public static Connection getDbConnection(String db) throws Exception {
- java.sql.Connection conn = null;
- try {
- LOG.debug("getting db connection for " + db + " ...");
- // Get the SampleUtilService from the Bridge
- SampleUtilService sampleUtilService = SpringContextBridge.services().getSampleUtilService();
- // Get DataSource from the JndiObjectFactoryBean
- javax.sql.DataSource ds = sampleUtilService.getDataSourcefromFactoryBean(db);
- conn = ds.getConnection();
- LOG.debug("got db connection for " + db);
- LOG.debug("url = " + conn.getMetaData().getURL());
- } catch (Exception e) {
- String message = String.format("Exception thrown while creating a JDBC connection for %s: %s", db,
- e.getMessage());
- throw new Exception(message);
- }
- return conn;
- }
- @Bean(destroyMethod="")
- public DataSource jndiDataSource() throws IllegalArgumentException, NamingException {
- JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
- bean.setJndiName("java:comp/env/jdbc/myDataSource");
- bean.setProxyInterface(DataSource.class);
- bean.setLookupOnStartup(false);
- bean.afterPropertiesSet();
- return (DataSource)bean.getObject();
- }
- DataSource dataSource =
- (DataSource) new InitialContext().lookup("java:comp/env/jdbc/myDataSource");
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement