001/* 002 * (C) Copyright 2012 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * Florent Guillaume 018 */ 019package org.nuxeo.ecm.core.persistence; 020 021import java.sql.Connection; 022import java.sql.SQLException; 023import java.util.Properties; 024 025import javax.naming.NamingException; 026import javax.sql.DataSource; 027import org.hibernate.HibernateException; 028import org.hibernate.cfg.Environment; 029import org.hibernate.connection.ConnectionProvider; 030import org.nuxeo.runtime.datasource.DataSourceHelper; 031 032/** 033 * ConnectionProvider for Hibernate that looks up the datasource 034 * from the nuxeo's container. 035 * 036 * @since 5.7 037 */ 038public class NuxeoConnectionProvider implements ConnectionProvider { 039 040 protected DataSource ds; 041 042 @Override 043 public void configure(Properties props) { 044 String name = props.getProperty(Environment.DATASOURCE); 045 try { 046 ds = DataSourceHelper.getDataSource(name); 047 } catch (NamingException cause) { 048 throw new HibernateException("Cannot lookup datasource by name " + name, cause); 049 } 050 } 051 052 @Override 053 public Connection getConnection() throws SQLException { 054 return ds.getConnection(); 055 } 056 057 @Override 058 public void closeConnection(Connection connection) throws SQLException { 059 connection.close(); 060 } 061 062 @Override 063 public void close() throws HibernateException { 064 ds = null; 065 } 066 067 @Override 068 public boolean supportsAggressiveRelease() { 069 // don't try to close the connection after each statement 070 // (not used if connection release mode is auto) 071 return false; 072 } 073 074}