2 * Copyright 2017 ZTE Corporation.
\r
4 * Licensed under the Apache License, Version 2.0 (the "License");
\r
5 * you may not use this file except in compliance with the License.
\r
6 * You may obtain a copy of the License at
\r
8 * http://www.apache.org/licenses/LICENSE-2.0
\r
10 * Unless required by applicable law or agreed to in writing, software
\r
11 * distributed under the License is distributed on an "AS IS" BASIS,
\r
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
\r
13 * See the License for the specific language governing permissions and
\r
14 * limitations under the License.
\r
16 package org.openo.holmes.common.utils;
\r
18 import io.dropwizard.db.DataSourceFactory;
\r
19 import io.dropwizard.jdbi.DBIFactory;
\r
20 import io.dropwizard.setup.Environment;
\r
21 import javax.inject.Inject;
\r
22 import javax.inject.Singleton;
\r
23 import lombok.extern.slf4j.Slf4j;
\r
24 import org.glassfish.hk2.api.IterableProvider;
\r
25 import org.jvnet.hk2.annotations.Service;
\r
26 import org.skife.jdbi.v2.DBI;
\r
27 import org.skife.jdbi.v2.Handle;
\r
32 public class DbDaoUtil {
\r
34 private static DBI jdbi;
\r
37 private static IterableProvider<Environment> environmentProvider;
\r
40 private static IterableProvider<DataSourceFactory> dataSourceFactoryProvider;
\r
44 synchronized (DbDaoUtil.class) {
\r
46 final DBIFactory factory = new DBIFactory();
\r
48 .build(environmentProvider.get(), dataSourceFactoryProvider.get(), "mysql");
\r
54 public <K> K getDao(Class<K> clazz) {
\r
56 return jdbi.open(clazz);
\r
57 } catch (Exception e) {
\r
58 log.warn("get object instance of Dao error.", e);
\r
63 public Handle getHandle() {
\r
66 } catch (Exception e) {
\r
67 log.warn("get object instance of Dao error.", e);
\r
72 public void close(Object obj) {
\r
76 } catch (Exception e) {
\r
77 log.warn("close jdbi connection error.", e);
\r
82 public <T> T getJdbiDaoByOnDemand(Class<T> daoClazz) {
\r
84 return jdbi.onDemand(daoClazz);
\r
88 public <T> T getJdbiDaoByOpen(Class<T> daoClazz) {
\r
90 return jdbi.open(daoClazz);
\r