1 package net.sumaris.core.dao.technical.hibernate;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 import org.hibernate.HibernateException;
29 import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
30 import org.hibernate.exception.spi.Configurable;
31 import org.hibernate.service.UnknownUnwrapTypeException;
32 import org.hibernate.service.spi.Stoppable;
33
34 import javax.sql.DataSource;
35 import java.sql.Connection;
36 import java.sql.SQLException;
37 import java.util.Properties;
38
39
40
41
42 public class HibernateConnectionProvider implements ConnectionProvider,Configurable,Stoppable {
43
44 private static final long serialVersionUID = 6463355546534159477L;
45
46 private static DataSource dataSource = null;
47
48 private static Connection connection = null;
49
50
51 @Override
52 public void configure(Properties props) throws HibernateException {
53 if (dataSource == null && connection == null) {
54 throw new HibernateException("DataSource must be set before using ConnectionProvider.");
55 }
56 }
57
58
59 @Override
60 public Connection getConnection() throws SQLException {
61 return dataSource != null ? dataSource.getConnection() : connection;
62 }
63
64
65 @Override
66 public void closeConnection(Connection conn) throws SQLException {
67 if (conn != null && !conn.isClosed()) {
68 conn.close();
69 }
70 }
71
72
73 @Override
74 public void stop(){
75
76 dataSource = null;
77 connection = null;
78 }
79
80
81 @Override
82 public boolean supportsAggressiveRelease() {
83
84 return false;
85 }
86
87
88
89
90
91
92 public static DataSource getDataSource() {
93 return dataSource;
94 }
95
96
97
98
99
100
101 public static void setDataSource(DataSource dataSource) {
102 HibernateConnectionProvider.dataSource = dataSource;
103 }
104
105
106
107
108
109
110 public static void setConnection(Connection connection) {
111 HibernateConnectionProvider.connection = connection;
112 }
113
114
115 @SuppressWarnings("rawtypes")
116 @Override
117 public boolean isUnwrappableAs(Class unwrapType) {
118 return ConnectionProvider.class.equals(unwrapType) ||
119 HibernateConnectionProvider.class.isAssignableFrom(unwrapType);
120 }
121
122
123 @SuppressWarnings("unchecked")
124 @Override
125 public <T> T unwrap(Class<T> unwrapType) {
126 if (ConnectionProvider.class.equals(unwrapType) ||
127 HibernateConnectionProvider.class.isAssignableFrom(unwrapType)) {
128 return (T) this;
129 } else {
130 throw new UnknownUnwrapTypeException(unwrapType);
131 }
132 }
133
134 }