1 /*
2 * Hibernate, Relational Persistence for Idiomatic Java
3 *
4 * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
5 * indicated by the @author tags or express copyright attribution
6 * statements applied by the authors. All third-party contributions are
7 * distributed under license by Red Hat Middleware LLC.
8 *
9 * This copyrighted material is made available to anyone wishing to use, modify,
10 * copy, or redistribute it subject to the terms and conditions of the GNU
11 * Lesser General Public License, as published by the Free Software Foundation.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
15 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
16 * for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public License
19 * along with this distribution; if not, write to:
20 * Free Software Foundation, Inc.
21 * 51 Franklin Street, Fifth Floor
22 * Boston, MA 02110-1301 USA
23 *
24 */
25 package org.hibernate.tool.hbm2ddl;
26
27 import org.hibernate.connection.ConnectionProvider;
28 import org.hibernate.util.JDBCExceptionReporter;
29
30 import java.sql.Connection;
31 import java.sql.SQLException;
32
33 /**
34 * A {@link ConnectionHelper} implementation based on a provided
35 * {@link ConnectionProvider}. Essentially, ensures that the connection
36 * gets cleaned up, but that the provider itself remains usable since it
37 * was externally provided to us.
38 *
39 * @author Steve Ebersole
40 */
41 class SuppliedConnectionProviderConnectionHelper implements ConnectionHelper {
42 private ConnectionProvider provider;
43 private Connection connection;
44 private boolean toggleAutoCommit;
45
46 public SuppliedConnectionProviderConnectionHelper(ConnectionProvider provider) {
47 this.provider = provider;
48 }
49
50 public void prepare(boolean needsAutoCommit) throws SQLException {
51 connection = provider.getConnection();
52 toggleAutoCommit = needsAutoCommit && !connection.getAutoCommit();
53 if ( toggleAutoCommit ) {
54 try {
55 connection.commit();
56 }
57 catch( Throwable ignore ) {
58 // might happen with a managed connection
59 }
60 connection.setAutoCommit( true );
61 }
62 }
63
64 public Connection getConnection() throws SQLException {
65 return connection;
66 }
67
68 public void release() throws SQLException {
69 // we only release the connection
70 if ( connection != null ) {
71 JDBCExceptionReporter.logAndClearWarnings( connection );
72 if ( toggleAutoCommit ) {
73 connection.setAutoCommit( false );
74 }
75 provider.closeConnection( connection );
76 connection = null;
77 }
78 }
79 }