Java org.skife.jdbi.v2.DBI 代码实例

・19 分钟阅读

以下是展示如何使用org.skife.jdbi.v2.DBI的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


@Override
public void fire(final Connection conn, final Object[] oldRow, final Object[] newRow)
                throws SQLException {
        final String id = (String) newRow[0];
        final BigDecimal newVersion = (BigDecimal) newRow[1]; 
        DBI dbi = new DBI(new ConnectionFactory() {
                @Override
                public Connection openConnection() throws SQLException {
                        return conn;
                }
        });
        Handle h = dbi.open();
        String sql1 = String.format("select version from %s where id = :id", aggregateRootTable);
        log.debug(sql1);
        BigDecimal lastVersion = h.createQuery(sql1).bind("id", id).map(BigDecimalMapper.FIRST).first();
        log.debug("uowTable, arTable, id {}, old version {}, new version {}", targetTable, aggregateRootTable, id, lastVersion, newVersion);
        if (lastVersion==null){
                validateAndProceedOnAggregateRootTable(id, newVersion, h);
        } else {
                validateAndProceedOnUnitOfWorkTable(id, newVersion, h, lastVersion);
        }
        String sqlSequence = String.format("SELECT seq_%s.nextval from dual", targetTable);
        BigDecimal next = h.createQuery(sqlSequence).map(BigDecimalMapper.FIRST).first();
        newRow[3] = next; // seq_number assignment (does it really work this way ?)
        log.debug("next --> {}", next);
}
 

实例 2


@BeforeMethod
public void setUp() throws Exception {
    handle = DBI.open(JDBC_URL);
    createSchema();
    getScenario().create(handle);
    UnitOfWork unitOfWork = new JooqUnitOfWork(handle.getConnection());
    unitOfWorkService = new UnitOfWorkService() {
        @Override
        public UnitOfWork getCurrent() {
            return unitOfWork;
        }
        @Override
        public UnitOfWork start() {
            return unitOfWork;
        }
        @Override
        public void commit() {
        }
        @Override
        public void abort() {
        }
    };
}
 

实例 3


public static <K, R> R execute(final Connection connection, final InTransactionHandler<K, R> handler, final Class<K> klass) {
    final DBI dbi = buildDDBI(connection);
    final Handle handle = dbi.open();
    try {
        final K transactional = handle.attach(klass);
        return handler.withSqlDao(transactional);
    } catch (final Exception e) {
        logger.error("Failed to process transaction", e);
        return null;
    } finally {
        // We do not release the connection -- client is responsible for closing it
        // h.close();
    }
}
 

实例 4


@Before
public void setup() throws ClassNotFoundException
{
    DataSource ds = JdbcConnectionPool.create("jdbc:h2:mem:test", "sa", "sa");
    DBI dbi = new DBI(ds);
    Handle h = dbi.open();
    h.execute(table);
    h.close();
    measurementDao = dbi.open(MeasurementDao.class);
}
 

实例 5


public H2QueryRunner()
{
    handle = DBI.open("jdbc:h2:mem:test" + System.nanoTime());
    TpchMetadata tpchMetadata = new TpchMetadata("");
    handle.execute("CREATE TABLE orders (n" +
            "  orderkey BIGINT PRIMARY KEY,n" +
            "  custkey BIGINT NOT NULL,n" +
            "  orderstatus CHAR(1) NOT NULL,n" +
            "  totalprice DOUBLE NOT NULL,n" +
            "  orderdate DATE NOT NULL,n" +
            "  orderpriority CHAR(15) NOT NULL,n" +
            "  clerk CHAR(15) NOT NULL,n" +
            "  shippriority BIGINT NOT NULL,n" +
            "  comment VARCHAR(79) NOT NULLn" +
            ")");
    handle.execute("CREATE INDEX custkey_index ON orders (custkey)");
    TpchTableHandle ordersHandle = tpchMetadata.getTableHandle(null, new SchemaTableName(TINY_SCHEMA_NAME, ORDERS.getTableName()));
    insertRows(tpchMetadata.getTableMetadata(null, ordersHandle), handle, createTpchRecordSet(ORDERS, ordersHandle.getScaleFactor()));
    handle.execute("CREATE TABLE lineitem (n" +
            "  orderkey BIGINT,n" +
            "  partkey BIGINT NOT NULL,n" +
            "  suppkey BIGINT NOT NULL,n" +
            "  linenumber BIGINT,n" +
            "  quantity BIGINT NOT NULL,n" +
            "  extendedprice DOUBLE NOT NULL,n" +
            "  discount DOUBLE NOT NULL,n" +
            "  tax DOUBLE NOT NULL,n" +
            "  returnflag CHAR(1) NOT NULL,n" +
            "  linestatus CHAR(1) NOT NULL,n" +
            "  shipdate DATE NOT NULL,n" +
            "  commitdate DATE NOT NULL,n" +
            "  receiptdate DATE NOT NULL,n" +
            "  shipinstruct VARCHAR(25) NOT NULL,n" +
            "  shipmode VARCHAR(10) NOT NULL,n" +
            "  comment VARCHAR(44) NOT NULL,n" +
            "  PRIMARY KEY (orderkey, linenumber)" +
            ")");
    TpchTableHandle lineItemHandle = tpchMetadata.getTableHandle(null, new SchemaTableName(TINY_SCHEMA_NAME, LINE_ITEM.getTableName()));
    insertRows(tpchMetadata.getTableMetadata(null, lineItemHandle), handle, createTpchRecordSet(LINE_ITEM, lineItemHandle.getScaleFactor()));
}
 

实例 6


/**
 * ??????????
 */
public static void initialize() {
        log.info("database initialize.");
        ds.set(createConnection());
        final DBI dbi = new DBI(ds.get());
        final RelationQueries relation = dbi.open(RelationQueries.class);
        relation.createRelationTable();
        relation.close();
        final BeginWord beginWord = dbi.open(BeginWord.class);
        beginWord.createBeginWordTable();
        beginWord.close();
        log.info("database initialized.");
}
 

实例 7


@ForMetadata
@Singleton
@Provides
public IDBI createDBI(@ForMetadata ConnectionFactory connectionFactory, TypeManager typeManager)
{
    DBI dbi = new DBI(connectionFactory);
    dbi.registerMapper(new TableColumn.Mapper(typeManager));
    return dbi;
}
 

实例 8


@Override
public DBI build(Environment environment,
                 PooledDataSourceFactory configuration,
                 ManagedDataSource dataSource,
                 String name) {
    final DBI dbi = super.build(environment, configuration, dataSource, name);
    dbi.registerArgumentFactory(new OptionalArgumentFactory(configuration.getDriverClass()));
    dbi.registerContainerFactory(new OptionalContainerFactory());
    dbi.registerArgumentFactory(new LocalDateArgumentFactory());
    dbi.registerArgumentFactory(new OptionalLocalDateArgumentFactory());
    dbi.registerArgumentFactory(new LocalDateTimeArgumentFactory());
    dbi.registerArgumentFactory(new OptionalLocalDateTimeArgumentFactory());
    dbi.registerMapper(new LocalDateMapper());
    dbi.registerMapper(new LocalDateTimeMapper());
    final Optional<TimeZone> tz = Optional.ofNullable(databaseTimeZone().orNull());
    dbi.registerArgumentFactory(new InstantArgumentFactory(tz));
    dbi.registerArgumentFactory(new OptionalInstantArgumentFactory(tz));
    dbi.registerMapper(new InstantMapper(tz));
    return dbi;
}
 

实例 9


@Override
public DBI createDBI(Properties properties) {
    DBI dbi = new DBI(properties.getProperty("db.url"), properties.getProperty("db.username"),
            properties.getProperty("db.password"));
    dbi.setSQLLog(new LogbackLog((Logger) LoggerFactory.getLogger(DBI.class), Level.INFO));
    dbi.setStatementRewriter(new NamePrependingStatementRewriter(new ColonPrefixNamedParamStatementRewriter()));
    dbi.registerArgumentFactory(new OptionalArgumentFactory(null));
    dbi.registerContainerFactory(new ImmutableListContainerFactory());
    dbi.registerContainerFactory(new ImmutableSetContainerFactory());
    dbi.registerContainerFactory(new OptionalContainerFactory());
    dbi.registerArgumentFactory(new JodaDateTimeArgumentFactory());
    dbi.registerMapper(new JodaDateTimeMapper(Optional.<TimeZone>absent()));
    return dbi;
}
 

实例 10


@Override
public synchronized IDBI getDBI() throws IOException {
    final DBI dbi = (DBI) super.getDBI();
    dbi.registerMapper(new AuditLogModelDaoMapper());
    dbi.registerMapper(new RecordIdIdMappingsMapper());
    dbi.registerMapper(new LowerToCamelBeanMapperFactory(SessionModelDao.class));
    return dbi;
}
 

实例 11


/**
 * Setup the database connection, DbUnit, DBI and service manager before each test class
 */
@BeforeClass
public static void setupServices() throws Exception {
    PGPoolingDataSource ds = new PGPoolingDataSource();
    ds.setServerName(POSTGRES_HOST);
    ds.setDatabaseName(POSTGRES_DBNAME);
    ds.setUser(POSTGRES_USERNAME);
    try {
        s_connection = new DatabaseConnection(ds.getConnection(), "public");
        s_connection.getConfig().setProperty(DatabaseConfig.FEATURE_CASE_SENSITIVE_TABLE_NAMES, Boolean.TRUE);
        s_connection.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new PostgresqlDataTypeFactoryExt());
        InputStream is = BaseServicesTest.class.getClassLoader().getResourceAsStream(INITIAL_DATASET);
        s_initialData = new FlatXmlDataSetBuilder().setColumnSensing(true).build(is);
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    DatabaseOperation.CLEAN_INSERT.execute(s_connection, s_initialData);
    DBI dbi = new DBI(ds);
    dbi.setSQLLog(new LogbackLog());
    dbi.registerMapper(new AnnotationMapperFactory());
    // initialise the cache
    s_cache = new Cache(REDIS_HOST, REDIS_DATABASE);
    s_cache.start();
    s_temba = new TembaManager(s_cache, "http://temba.example.com/api/v1", "12345", false);
    s_temba.start();
    // initialise the service manager (all DAOs, services)
    s_services = new ServiceManager(dbi, s_cache, s_temba, false);
    s_services.start();
}
 

实例 12


@Singleton
@Provides
public DBI provideDBI(ObjectMapper objectMapper)
        throws ClassNotFoundException
{
    final DBIFactory factory = new DBIFactory();
    final DBI dbi =  factory.build(environment, config.getDataSourceFactory(), "mysql");
    dbi.registerMapper(new TableRow.TableRowMapper(objectMapper));
    dbi.registerMapper(new QueryStoreMapper(objectMapper));
    dbi.registerArgumentFactory(new UUIDArgumentFactory());
    dbi.registerArgumentFactory(new URIArgumentFactory());
    return dbi;
}
 

实例 13


@BeforeClass(groups = "slow")
public void beforeClass() throws Exception {
    loadSystemPropertiesFromClasspath("/queue.properties");
    clock = new ClockMock();
    embeddedDB = new MySQLEmbeddedDBWithDataSource("killbillq", "killbillq", "killbillq", false);
    embeddedDB.initialize();
    embeddedDB.start();
    embeddedDB.overwriteDataSource();
    final String ddl = toString(Resources.getResource("org/killbill/queue/ddl.sql").openStream());
    embeddedDB.executeScript(ddl);
    embeddedDB.refreshTableNames();
    databaseTransactionNotificationApi = new DatabaseTransactionNotificationApi();
    dbi = new DBI(embeddedDB.getDataSource());
    dbi.registerArgumentFactory(new UUIDArgumentFactory());
    dbi.registerArgumentFactory(new DateTimeZoneArgumentFactory());
    dbi.registerArgumentFactory(new DateTimeArgumentFactory());
    dbi.registerArgumentFactory(new LocalDateArgumentFactory());
    dbi.registerMapper(new UUIDMapper());
    dbi.setTransactionHandler(new NotificationTransactionHandler(databaseTransactionNotificationApi));
    final ConfigSource configSource = new SimplePropertyConfigSource(System.getProperties());
    persistentBusConfig = new ConfigurationObjectFactory(configSource).buildWithReplacements(PersistentBusConfig.class,
            ImmutableMap.<String, String>of("instanceName", "main"));
    notificationQueueConfig = new ConfigurationObjectFactory(configSource).buildWithReplacements(NotificationQueueConfig.class,
            ImmutableMap.<String, String>of("instanceName", "main"));
}
 

实例 14


public static DBI get(final DataSource dataSource) {
    final DBI dbi = new DBI(dataSource);
    dbi.registerMapper(new LowerToCamelBeanMapperFactory(BusinessAccountFieldModelDao.class));
    dbi.registerMapper(new LowerToCamelBeanMapperFactory(BusinessAccountModelDao.class));
    dbi.registerMapper(new LowerToCamelBeanMapperFactory(BusinessAccountTagModelDao.class));
    dbi.registerMapper(new LowerToCamelBeanMapperFactory(BusinessInvoiceAdjustmentModelDao.class));
    dbi.registerMapper(new LowerToCamelBeanMapperFactory(BusinessInvoiceFieldModelDao.class));
    dbi.registerMapper(new LowerToCamelBeanMapperFactory(BusinessInvoiceItemAdjustmentModelDao.class));
    dbi.registerMapper(new LowerToCamelBeanMapperFactory(BusinessInvoiceItemCreditModelDao.class));
    dbi.registerMapper(new LowerToCamelBeanMapperFactory(BusinessInvoiceItemModelDao.class));
    dbi.registerMapper(new LowerToCamelBeanMapperFactory(BusinessInvoiceModelDao.class));
    dbi.registerMapper(new LowerToCamelBeanMapperFactory(BusinessInvoicePaymentFieldModelDao.class));
    dbi.registerMapper(new LowerToCamelBeanMapperFactory(BusinessPaymentAuthModelDao.class));
    dbi.registerMapper(new LowerToCamelBeanMapperFactory(BusinessPaymentCaptureModelDao.class));
    dbi.registerMapper(new LowerToCamelBeanMapperFactory(BusinessPaymentPurchaseModelDao.class));
    dbi.registerMapper(new LowerToCamelBeanMapperFactory(BusinessPaymentRefundModelDao.class));
    dbi.registerMapper(new LowerToCamelBeanMapperFactory(BusinessPaymentCreditModelDao.class));
    dbi.registerMapper(new LowerToCamelBeanMapperFactory(BusinessPaymentChargebackModelDao.class));
    dbi.registerMapper(new LowerToCamelBeanMapperFactory(BusinessInvoicePaymentTagModelDao.class));
    dbi.registerMapper(new LowerToCamelBeanMapperFactory(BusinessInvoiceTagModelDao.class));
    dbi.registerMapper(new LowerToCamelBeanMapperFactory(BusinessAccountTransitionModelDao.class));
    dbi.registerMapper(new LowerToCamelBeanMapperFactory(BusinessSubscriptionTransitionModelDao.class));
    dbi.registerMapper(new LowerToCamelBeanMapperFactory(BusinessBundleModelDao.class));
    dbi.registerMapper(new LowerToCamelBeanMapperFactory(BusinessBundleFieldModelDao.class));
    dbi.registerMapper(new LowerToCamelBeanMapperFactory(BusinessBundleTagModelDao.class));
    dbi.registerMapper(new LowerToCamelBeanMapperFactory(CurrencyConversionModelDao.class));
    dbi.registerMapper(new LowerToCamelBeanMapperFactory(ReportsConfigurationModelDao.class));
    dbi.registerMapper(new UUIDMapper());
    dbi.registerArgumentFactory(new UUIDArgumentFactory());
    dbi.registerArgumentFactory(new DateTimeZoneArgumentFactory());
    dbi.registerArgumentFactory(new DateTimeArgumentFactory());
    dbi.registerArgumentFactory(new LocalDateArgumentFactory());
    dbi.setStatementLocator(new AnalyticsStatementLocator());
    dbi.setSQLLog(new Slf4jLogging());
    final DatabaseTransactionNotificationApi databaseTransactionNotificationApi = new DatabaseTransactionNotificationApi();
    final TransactionHandler notificationTransactionHandler = new NotificationTransactionHandler(databaseTransactionNotificationApi);
    dbi.setTransactionHandler(new RestartTransactionRunner(notificationTransactionHandler));
    return dbi;
}
 

实例 15


@Override
public DBI get() {
  try {
    DBI dbi = dbiFactory.build(environment, dataSourceFactory, "db");
    for (ResultSetMapper<?> resultSetMapper : resultSetMappers) {
      dbi.registerMapper(resultSetMapper);
    }
    return dbi;
  } catch (ClassNotFoundException e) {
    throw new ProvisionException("while instantiating DBI", e);
  }
}
 
讨论
淘淘あ西西 profile image