Datasource oracle что это
When you start with Spring Boot, it will automatically support H2 if no other data sources have been defined and H2 is found on the classpath. I’ve been using H2 for development for sometime now. It works very well. All modern relational databases are going to support ANSI SQL. But each is going to have its own nuances and extensions. One thing of the things I like about H2 is its Oracle compatibility mode. It allows H2 to act like an Oracle database. It’s not perfect, but it does do a pretty good job.
The Spring Framework is the most popular Java framework used for building enterprise class applications. Oracle is the most popular database used in the enterprise. So chances are, if you are developing Spring Applications, sooner or later, you’re going to be persisting to an Oracle database.
The Oracle JDBC drivers are not in public Maven repositories due to legal restrictions. This is really rather annoying. Oracle, if you’re reading this – really? Come on, fix this. Please.
So, if you are in a company, chances are you will have a Nexus installation with the Oracle JDBC jar installed. But if you are not, you will need to download the JDBC driver from Oracle (after accepting the terms and conditions you probably won’t read). And then you can install it into your local Maven repository manually.
You can install a JAR into your Maven repository using this Maven command. You may need to adjust the version and name depending on the JDBC driver version you download.
Пул подключений
Пулу подключений в спецификации JDBC отведен раздел "Chapter 11 Connection Pooling". В нём же и даётся главное обоснование необходимости пула подключений. Каждый Coonection - это физическое подключение к БД. Его создание и закрытие - довольно "дорогая" работа. JDBC предоставляет лишь API для пула соединений. Поэтому, выбор реализации остаётся за нами. Например, к таким реализациям относится HikariCP. Соответственно, нам понадобится добавить пул к нам в зависимости проекта: Теперь надо как-то пул этот задействовать. Для этого нужно выполнить инициализацию источника данных, он же Datasource: И напишем тест на получение подключения из пула:
Источник данных Java. Пример источника данных JDBC. javax.sql.Источник данных, MysqlDataSource, OracleDataSource, DBCP Apache Commons, примеры баз данных MySQL и Oracle.
Программирование источников данных Java и источников данных JDBC-это способ работы с базой данных в наших программах java. Мы уже видели, что JDBC DriverManager можно использовать для подключения к реляционным базам данных. Но когда дело доходит до реального программирования, нам нужно нечто большее, чем просто связи.
Пример источника данных JDBC
Давайте создадим простой пример проекта источника данных JDBC и узнаем, как использовать базовые классы реализации MySQL и Oracle DataSource для подключения к базе данных. Наш окончательный проект будет выглядеть так, как показано на рисунке ниже.
Источник данных Java
В большинстве случаев мы ищем слабую связь для подключения, чтобы мы могли легко переключать базы данных, объединять пулы соединений для управления транзакциями и поддержки распределенных систем. Источник данных JDBC является предпочтительным подходом, если вы ищете любую из этих функций в своем приложении. Интерфейс источника данных Java присутствует в javax.sql пакете и объявляет только два перегруженных метода getConnection() и getConnection(Строка str1,строка str2) .
3.1.2 Datasource Features and Properties
With datasource functionality, using JNDI, you do not need to register the vendor-specific JDBC driver class name, and you can use logical names for URLs and other properties. This allows your application code for opening database connections to be portable to other environments.
3.1.2.1 DataSource Interf ace and Oracle Implementation
A JDBC datasource is an instance of a class that implements the standard javax.sql.DataSource interface:
Oracle implements this interface with the OracleDataSource class in the oracle.jdbc.pool package. The overloaded getConnection() method returns a physical connection to the database.
To use other values, you can set properties using appropriate setter methods discussed in the next section. For alternative user names and passwords, you can also use the getConnection() signature that takes these as input—this would take priority over the property settings.
Note:
3.1.2.2 DataSou rce Properties
The OracleDataSource class, as with any class that implements the DataSource interface, provides a set of properties that can be used to specify a database to connect to. These properties follow the JavaBeans design pattern.
Table 3-1 and Table 3-2 document OracleDataSource properties. The properties in Table 3-1 are standard properties according to the Sun Microsystems specification. (Be aware, however, that Oracle does not implement the standard roleName property.) The properties in Table 3-2 are Oracle extensions.
Table 3-1 Standard Datasource Properties
(Other possible settings include ipc . See the Oracle Net Services Administrator's Guide for more information.)
The OracleDataSource class implements the following setter and getter methods for the standard properties:
public synchronized void setDatabaseName(String dbname)
public synchronized String getDatabaseName()
public synchronized void setDataSourceName(String dsname)
public synchronized String getDataSourceName()
public synchronized void setDescription(String desc)
public synchronized String getDescription()
public synchronized void setNetworkProtocol(String np)
public synchronized String getNetworkProtocol()
public synchronized void setPassword(String pwd)
public synchronized void setPortNumber(int pn)
public synchronized int getPortNumber()
public synchronized void setServerName(String sn)
public synchronized String getServerName()
public synchronized void setUser(String user)
public synchronized String getUser()
Note that there is no getPassword() method, for security reasons.
Table 3-2 Oracle Extended Datasource Properties
Enable this OracleXADataSource property when using the HeteroRM feature with the OCI driver, to access Oracle pre-8.1.6 databases and higher. The HeteroRM XA feature is described in "OCI HeteroRM XA". If the tnsEntry property is not set when using the HeteroRM XA feature, an SQLException with error code ORA-17207 is thrown.
This DataSource property defaults to false .
Notes:
This table omits properties that supported the deprecated connection cache based on OracleConnectionCache.
Because nativeXA performs better than JavaXA, use nativeXA whenever possible.
void setConnectionCacheProperties(java.util.Properties cp)
void setConnectionProperties(java.util.Properties cp)
void setDriverType(String dt)
void setURL(String url)
void setTNSEntryName(String tns)
void setNativeXA(boolean nativeXA)
If you are using the server-side internal driver— driverType property is set to kprb —then any other property settings are ignored.
If you are using the Thin or OCI drivers, note the following:
A URL setting can include settings for user and password , as in the following example, in which case this takes precedence over individual user and password property settings:
Settings for user and password are required, either directly, through the URL setting, or through the getConnection() call. The user and password settings in a getConnection() call take precedence over any property settings.
If the url property is set, then any tnsEntry , driverType , portNumber , networkProtocol , serverName , and databaseName property settings are ignored.
If the tnsEntry property is set (which presumes the url property is not set), then any databaseName , serverName , portNumber , and networkProtocol settings are ignored.
If you are using an OCI driver (which presumes the driverType property is set to oci ) and the networkProtocol is set to ipc , then any other property settings are ignored.
Methods inherited from class java.lang.Object
Вступление
Одна из основных целей языка программирования - хранение и обработка информации. Чтобы лучше понять работу хранения данных стоит немного времени выделить на теорию и архитектуру приложений. Например, можно ознакомиться с литературой, а именно с книгой "Software Architect's Handbook: Become a successful software architect by implementing effective arch. " авторства Joseph Ingeno. Как сказано, есть некий Data Tier или "Слой данных". Он включает в себя место хранения данных (например, SQL базу данных) и средства для работы с хранилищем данных (например, JDBC, о котором и пойдёт речь). Так же на сайте Microsoft есть статья: "Проектирование уровня сохраняемости инфраструктуры" в которой описывается архитектурное решение выделения из Data Tier дополнительного слоя — Persistence Layer. В таком случае Data Tier — это уровень хранения самих данных, в то время как Persistence Layer - это некоторый уровень абстракции для работы с данными из хранилища с уровня Data Tier. К уровню Persistence Layer можно отнести шаблон "DAO" или различные ORM. Но ORM — это тема отдельного разговора. Как Вы могли уже понять, вначале появился Data Tier. Ещё с времён JDK 1.1 в Java мире появился JDBC (Java DataBase Connectivity — соединение с базами данных на Java). Это стандарт взаимодействия Java-приложений с различными СУБД, реализованный в виде пакетов java.sql и javax.sql, входящих в состав Java SE:
Данный стандарт описан специфкицией "JSR 221 JDBC 4.1 API". Данная спецификация рассказывает нам о том, что JDBC API предоставляет программный доступ к реляционным базам данных из программ, написанных на Java. Так же рассказывает о том, что JDBC API является частью платформы Java и входит поэтому в Java SE и Java EE. JDBC API представлен двумя пакетами: java.sql and javax.sql. Давайте тогда с ними и познакомимся.
Maven Dependency
You will need to add the Oracle Driver to your Maven (or Gradle) dependencies.
Method Summary
Modifier and Type | Method and Description |
---|---|
protected void | addRefProperties (Reference ref) |
void | close () |
Close DataSource API. This removes the associated Connection Cache and frees resources. This must be the last method to invoke, after the user is finished using a cache enabled DataSource.
Attempt to obtain a database connection from the Implicit Connection Cache using Connection Attributes
Attempt to obtain a database connection from the Implicit Connection Cache using user, passwd and Connection Attributes
Gets the maximum time in seconds that this data source can wait while attempting to connect to a database.
Return the ONS configuration string that is used for remote ONS subscription, in the form specified in setONSConfiguration(String). This is used by Fast Connection Failover and Runtime Load Balancing.
Get the service_name To distinguish services from instances, a new URL using service_name is added, existing url with SID will be supported, but deprecated.
Setter method to set one or more Implicit Connection Cache properties. If a null value is set, default values will take effect. Below are the list of properties supported. These are the keys (case sensitive) to be used when setting their appropriate values.
Setter method to enable Implicit Connection Caching
setExplicitCachingEnabled Sets the value of the explicitCachingEnabled property, which enables or disables the explicit cache.
setImplicitCachingEnabled Sets the value of the implicitCachingEnabled property, which enables or disables the implicit cache.
Sets the maximum time in seconds that this data source will wait while attempting to connect to a database.
Set the configuration string used for remote ONS subscription. The parameter string closely resembles the content of the ONS configuration file "ons.config", and contains a list of "=" pairs separated by newline character '\n', where can be one of "nodes", "walletfile", or "walletpassword". The parameter string should at least specify the ONS configuration attribute "nodes", as a list of host:port pairs separated by comma ','. SSL would be used when the "walletfile" attribute is specified as an Oracle wallet file.
An example ONS configuration string:
This is used primarily by Fast Connection Failover and Runtime Load Balancing.
Sets a supplier function that generates an access token when creating a connection with this DataSource .
Начало работы
Чтобы понять что такое вообще JDBC API нам понадобится Java приложение. Удобнее всего воспользоваться одной из систем сборки проектов. Например, воспользуемся Gradle. Более подробно про Gradle можно прочитать в небольшом обзоре: "Краткое знакомство с Gradle". Для начала инициализируем новый Gradle проект. Так как функциональность Gradle реализуется через плагины, то для инициализации нам нужно воспользоваться "Gradle Build Init Plugin": Откроем после этого билд скрипт — файл build.gradle, где описывается наш проект и то, как с ним нужно работать. Нас интересует блок "dependencies", где описываются зависимости — то есть те библиотеки/фрэймворки/api, без которых мы не можем работать и от которых мы зависим. По умолчанию мы увидим что-то вроде: Почему мы тут это видим? Это зависимости нашего проекта, которые нам сгенерировал автоматически Gradle при создании проекта. А так же потому что guava - это отдельная библиотека, не входящая в комплект с Java SE. JUnit так же не входит в комплект с Java SE. Но JDBC у нас есть "из коробки", то есть входит в состав Java SE. Получается JDBC у нас есть. Отлично. Что же нам ещё надо? Есть такая замечательная схема:
Как мы видим, и это логично, база данных является внешним компонентом, которого нет изначально в Java SE. Это объясняется просто - существует огромное количество баз данных и работать вы можете захотеть с любой. Например, есть PostgreSQL, Oracle, MySQL, H2. Каждая из этих баз данных поставляется отдельной компанией, которые называются поставщиками баз данных или database vendors. Каждая база данных написана на каком-то своём языке программирования (не обязательно Java). Чтобы с базой данных можно было работать из Java приложения поставщик базы данных пишет особый драйвер, который является своего образа адаптером. Такие JDBC совместимые (то есть у которых есть JDBC драйвер) ещё называют "JDBC-Compliant Database". Тут можно провести аналогию с компьютерными устройствами. Например, в блокноте есть кнопка "Печать". Каждый раз когда вы её нажимаете программа сообщает операционной системе, что приложение блокнот хочет напечатать. И у Вас есть принтер. Чтобы научить разговаривать единообразно вашу операционную систему с принтером Canon или HP понадобятся разные драйверы. Но для Вас, как пользователя, ничего не изменится. Вы по прежнему будете нажимать одну и ту же кнопку. Так и с JDBC. Вы выполняете один и тот же код, просто "под капотом" могут работать разные базы данных. Думаю, тут очень понятный подход. Каждый такой JDBC драйвер — это некоторый артефакт, библиотека, jar файл. Он то и является зависимостью для нашего проекта. Например, мы можем выбрать базу данных "H2 Database" и тогда нам надо добавить зависимость следующим образом: То, как найти зависимость и как её описать указано на официальных сайтах поставщика БД или на "Maven Central". JDBC драйвер не является базой данных, как Вы поняли. А лишь является проводником к ней. Но есть такое понятие, как "In memory databases". Это такие базы данных, которые существуют в памяти на время жизни вашего приложения. Обычно, это часто используют для тестирования или для учебных целей. Это позволяет не ставить отдельный сервер баз данных на машине. Что нам очень даже подойдёт для знакомств с JDBC. Вот и готова наша песочница и мы приступаем.
3.1.5 Logging and Tracing
The datasource facility offers a way to register a character stream for JDBC to use as output for error logging and tracing information. This facility allows tracing specific to a particular datasource instance. If you want all datasource instances to use the same character stream, then you must register the stream with each datasource instance individually.
The OracleDataSource class implements the following standard datasource methods for logging and tracing:
public synchronized void setLogWriter(PrintWriter pw)
public synchronized PrintWriter getLogWriter()
The PrintWriter class is in the standard java.io package.
Notes:
When a datasource instance is created, logging is disabled by default (the log stream name is initially null).
Messages written to a log stream registered to a datasource instance are not written to the same log stream used by DriverManager .
An OracleDataSource instance obtained from a JNDI name lookup will not have its PrinterWriter set, even if the PrintWriter was set when a datasource instance was first bound to this JNDI name.
Источник данных JDBC
Различные поставщики баз данных несут ответственность за предоставление различных видов реализации интерфейса источника данных. Например, драйвер MySQL JDBC обеспечивает базовую реализацию интерфейса источника данных с com.mysql.jdbc.jdbc2.необязательно.MysqlDataSource класс и драйвер базы данных Oracle реализуют его с помощью oracle.jdbc.pool.OracleDataSource Класс.
Эти классы реализации предоставляют методы, с помощью которых мы можем предоставить сведения о сервере базы данных с учетными данными пользователя. Некоторые из других общих функций, предоставляемых этими классами реализации источников данных JDBC, являются;
- Кэширование подготовленной инструкции для более быстрой обработки
- Настройки тайм-аута подключения
- Функции ведения журнала
- Порог максимального размера результирующего набора
3.1.1 A Brief Overview of Oracle Datasource Su pport for JNDI
The standard Java Naming and Directory Interface, or JNDI, provides a way for applications to find and access remote services and resources. These services can be any enterprise services, but for a JDBC application would include database connections and services.
JNDI allows an application to use logical names in accessing these services, removing vendor-specific syntax from application code. JNDI has the functionality to associate a logical name with a particular source for a desired service.
All Oracle JDBC datasources are JNDI-referenceable. The developer is not required to use this functionality, but accessing databases through JNDI logical names makes the code more portable.
Note:
RowSet
JDBC помимо ResultSet вводит такое понятие, как RowSet. Подробнее можно прочитать здесь: "JDBC Basics: Using RowSet Objects". Существуют различные вариации использования. Например, самый простой случай может выглядеть так: Как видно, RowSet похож на симбиоз statement (мы указали через него command) и выполнили command. Через него же мы управляем курсором (вызывая метод next) и из него же получаем данные. Интересен не только такой подход, но и возможные реализации. Например, CachedRowSet. Он является "отключённым" (то есть не использует постоянное подключение к БД) и требует явного выполнения синхронизации с БД: Подробнее можно прочитать в tutorial на сайте Oracle: "Using CachedRowSetObjects".
Field Summary
Oracle Properties
In this example, I’m going to show you how to externalise the Oracle connection properties to a properties file.
In our Spring Boot application.properties file we want to set the following properties.
Next, on our Configuration class for Oracle, we want to add the following annotation:
This tells Spring to look for the property prefix of Oracle when binding properties. Now if our configuration class has a property called ‘whatever’, Spring would try to bind the property value of ‘oracle.whatever’ to the property in the configuration class.
Now if we add the following properties to our configuration class, Spring will use them in the creation of our Oracle data source.
The final Oracle configuration class looks like this:
OracleConfiguration.class
Statements
- Statement: SQL выражение, которое не содержит параметров
- PreparedStatement : Подготовленное SQL выражение, содержащее входные параметры
- CallableStatement : SQL выражение с возможностью получить возвращаемое значение из хранимых процедур (SQL Stored Procedures).
ResultSet
Понятие ResultSet описано в спецификации JDBC API в главе "CHAPTER 15 Result Sets". Прежде всего, там сказано, что ResultSet предоставляет методы для получения и манипуляции результатами выполненных запросов. То есть если метод execute вернул нам true, значит мы можем получить и ResultSet. Давайте вынесем вызов метода createCustomerTable() в метод init, который отмечен как @Before. Теперь доработаем наш тест shouldSelectData: Тут стоит отметить, что next — это метод, который двигает так называемый "курсор". Курсор в ResultSet указывает на некоторую строку. Таким образом, чтобы считать строку, на неё нужно этот самый курсор установить. Когда курсор перемещается, то метод перемещения курсора возвращает true, если курсор валидный (правильный, корректный), то есть указывает на данные. Если возвращает false, значит данных нет, то есть курсор не указывает на данные. Если попытаться получить данные с невалидным курсором, то мы получим ошибку: No data is available Ещё интересно, что через ResultSet можно обновлять или даже вставлять строки:
Источник данных Java JDBC – Настройка базы данных
Прежде чем мы перейдем к нашим примерам программ, нам нужна некоторая настройка базы данных с таблицей и образцами данных. Установка базы данных MySQL или Oracle выходит за рамки этого руководства, поэтому я просто перейду к настройке таблицы с образцами данных.
Теперь давайте перейдем к нашим программам на java. Для того, чтобы конфигурация базы данных была слабо связана, я прочитаю их из файла свойств.
Убедитесь, что приведенные выше конфигурации соответствуют вашим локальным настройкам. Также убедитесь, что у вас есть JAR-файлы MySQL и Oracle DB JDBC, включенные в путь сборки проекта.
Connection
- Через DriverManager
- Через DataSource
Metadata
Кроме запросов, подключение к БД (т.е. экземпляр класса Connection) предоставляет доступ к метаданным - данным о том, как настроена и как устроена наша база данных. Но для начала озвучим несколько ключевых моментов: URL подключения к нашей БД: "jdbc:h2:mem:test". test - это название нашей базы данных. Для JDBC API это каталог. И название будет в верхнем регистре, то есть TEST. Схема по умолчанию (Default schema) для H2 - PUBLIC. Теперь, напишем тест, который показывает все пользовательские таблицы. Почему пользовательские? Потому что в базах данных есть не только пользовательские (те, которые мы сами создали при помощи create table выражений), но и системные таблицы. Они необходимы, чтобы хранить системную информацию о структуре БД. У каждой БД такие системные таблицы могут храниться по-разному. Например, в H2 они хранятся в схеме "INFORMATION_SCHEMA". Интересно, что INFORMATION SCHEMA является общим подходом, но Oracle пошли иным путём. Подробнее можно прочитать здесь: "INFORMATION_SCHEMA и Oracle". Напишем тест, получающий метаданные по пользовательским таблицам:
Method Detail
getConnection
Attempt to establish a database connection.
getConnection
Attempt to establish a database connection.
getConnection
getPhysicalConnection
getConnection
Attempt to obtain a database connection from the Implicit Connection Cache using Connection Attributes
getConnection
Attempt to obtain a database connection from the Implicit Connection Cache using user, passwd and Connection Attributes
close
Close DataSource API. This removes the associated Connection Cache and frees resources. This must be the last method to invoke, after the user is finished using a cache enabled DataSource.
setConnectionCachingEnabled
Setter method to enable Implicit Connection Caching
getConnectionCachingEnabled
setConnectionCacheName
getConnectionCacheName
setConnectionCacheProperties
Setter method to set one or more Implicit Connection Cache properties. If a null value is set, default values will take effect. Below are the list of properties supported. These are the keys (case sensitive) to be used when setting their appropriate values.
Sets limit on Minimum number of connections. Defaults to 0.
Sets limit on Maximum number of connections. No default.
Sets limit on the number of initial connections populated, when the cache is first created. Defaults to 0.
Sets the Maximum number of statements that each connection keeps open, for statement caching. Defaults to 0.
Sets the Maximum time, in seconds, a connection in the cache can remain idle (that is not checked out of the cache). Defaults to 0.
Sets that maximum time, in seconds, a checked out connection can remain idle. Defaults to 0.
Sets the maximum time a checked out connection can remain unused (no SQL activity) before the connection is closed and returned to the cache. Defaults to 0.
Specifies the time limit to wait, when a new connection request arrives, and there are no connections to check out. Defaults to 0.
Sets the time interval for the cache daemon thread to enforce the time out limits. Defaults to 900 seconds (15 minutes).
Verifies each connection for validity, before a checked out connection is returned to the caller. Defaults to false.
Causes the connection cache to retrieve the connection with the closest approximation to the specified connection attributes. Defaults to false.
Sets the weight (integer) for each connection attribute. This is used when ClosestConnectionMatch is set to true, and enables retrieval of a connection with the highest combined weight of all its connection attributes. Defaults to a weight of 1.
Sets the lower threshold limit on the cache. This is used for the releaseConnection() cache callback method is registered. Defaults to 20%.
getConnectionCacheProperties
setFastConnectionFailoverEnabled
getFastConnectionFailoverEnabled
getONSConfiguration
Return the ONS configuration string that is used for remote ONS subscription, in the form specified in setONSConfiguration(String). This is used by Fast Connection Failover and Runtime Load Balancing.
setONSConfiguration
Set the configuration string used for remote ONS subscription. The parameter string closely resembles the content of the ONS configuration file "ons.config", and contains a list of "=" pairs separated by newline character '\n', where can be one of "nodes", "walletfile", or "walletpassword". The parameter string should at least specify the ONS configuration attribute "nodes", as a list of host:port pairs separated by comma ','. SSL would be used when the "walletfile" attribute is specified as an Oracle wallet file.
An example ONS configuration string:
This is used primarily by Fast Connection Failover and Runtime Load Balancing.
getLoginTimeout
Gets the maximum time in seconds that this data source can wait while attempting to connect to a database. A value of zero means that the timeout is the default system timeout if there is one; otherwise it means that there is no timeout. When a DataSource object is created the login timeout is initially zero.
setLoginTimeout
Sets the maximum time in seconds that this data source will wait while attempting to connect to a database. A value of zero specifies that the timeout is the default system timeout if there is one; otherwise it specifies that there is no timeout. When a DataSource object is created the login timeout is initially zero.
setLogWriter
Set the log writer for this data source.
The log writer is a character output stream to which all logging and tracing messages for this data source object instance will be printed. This includes messages printed by the methods of this object, messages printed by methods of other objects manufactured by this object, and so on. Messages printed to a data source specific log writer are not printed to the log writer associated with the java.sql.Drivermanager class. When a DataSource object is created the log writer is initially null, in other words, logging is disabled.
getLogWriter
Get the log writer for this data source.
The log writer is a character output stream to which all logging and tracing messages for this data source object instance will be printed. This includes messages printed by the methods of this object, messages printed by methods of other objects manufactured by this object, and so on. Messages printed to a data source specific log writer are not printed to the log writer associated with the java.sql.Drivermanager class. When a DataSource object is created the log writer is initially null, in other words, logging is disabled.
setTNSEntryName
Set the TNS entry name. Works only for JDBC OCI driver. Assumed that client side Oracle in installed and TNS_ADMIN env variable is set. If URL is set, this property will be ignored.
getTNSEntryName
setDataSourceName
Set the DataSourceName. Users need not set this as it will be set set automatically depending upon the instance created. Returns OracleDataSource for an OracleDataSource instance. Returns OracleXADataSource for an OracleXADataSource instance.
getDataSourceName
getDatabaseName
setDatabaseName
Set the name of a particular database on a server. In Oracle's jargon this is called SID (System Identifier).
If URL is set, this property will be ignored.
setServiceName
Set the service_name of a database on a server. If URL is set, this property will be ignored. To distinguish services from instances, a new URL using service_name is added, existing url with SID will be supported, but deprecated.
getServiceName
Get the service_name To distinguish services from instances, a new URL using service_name is added, existing url with SID will be supported, but deprecated.
setServerName
Set the name of the Server on which database is running. If URL is set, this property will be ignored.
getServerName
setURL
Set the URL from which connections have to be obtained. If URL is set all other properties like databasename, servername, portNumber, network protocol, tnsentry, and driver Type will be ignored.
getURL
Get the URL for this datasource. Will return the default value "jdbc:oracle:oci8:@" if not set before.
setUser
getUser
setPassword
getPassword
getDescription
setDescription
getDriverType
setDriverType
Set the JDBC driver type. Possible values are thin, oci8, and kprb. If URL is set, this property will be ignored.
If set to kprb, nothing else is needed to open a connection. This is meant for Server side JDBC driver when running inside server.
If set to thin, serverName, portNumber and databaseName are need to open a connection.
If set to oci, and network protocol is set to IPC or TNSEntryName is set then nothing else is needed. If not, serverName, portNumber and databaseName have to be provided.
getNetworkProtocol
setNetworkProtocol
Set the network protocol for the connections. Default is "tcp". Can be set to all possible protocols Net8 supports. Only needed for JDBC OCI driver.
This chapter discusses connecting applications to databases using JDBC datasources, as well as the URLs that describe databases. It is divided into the following sections:
Spring Boot Basic Configuration for Oracle
Источник данных Java JDBC – MySQL, пример Oracle
Давайте напишем фабричный класс, который мы можем использовать для получения источника данных MySQL или Oracle.
Обратите внимание, что классы реализации источников данных Oracle и MySQL очень похожи, давайте напишем простую тестовую программу для использования этих методов и проведем некоторый тест.
Обратите внимание, что класс клиента полностью независим от каких-либо классов, специфичных для базы данных. Это помогает нам скрыть основные детали реализации от клиентской программы и добиться слабой связи и преимуществ абстракции.
Когда мы запустим вышеописанную тестовую программу, мы получим результат ниже.
3.2 Database URLs and Database Specifiers
Database URLs are strings. The complete URL syntax is:
Notes:
The brackets indicate that the username / password pair is optional.
kprb, the internal server-side driver, uses an implicit connection; database URLs for the server-side driver end after the driver_type . See "Connecting to the Database with the Server-Side Internal Driver".
The Thin driver does not support OS authentication in making the connection, and therefore does not support special logins.
database specifier, which uniquely identifies the database to which the application is connected. Some database specifiers are valid only for the Thin driver, some only for the OCI driver, and some for both.
Hibernate Configuration
We will want to tell Hibernate to use the Oracle dialect. We do this by adding the following property to the Spring Boot application.properties file.
Required
Optional
If you’re used to using the H2 database, database tables will automatically be generated by Hibernate. If you want the same behavior in Oracle, you’ll need to set the ddl-auto property of Hibernate to ‘create-drop’. The Spring Boot documentation has additional information about database initialization. To have tables automatically created in Oracle, set the following property in your application.properties file.
In testing the code for this post, I spooled up an Oracle instance using Amazon RDS. This makes creating an Oracle database crazy easy. If you want to test this out yourself, I’ve checked in the code on GitHub here. You can check it out, and setup your own Oracle instance on Amazon RDS. Just update the connection properties in application.properities. I branched the code from my tutorial series on building a web application with Spring Boot. Everything will work – EXCEPT create and save. Oracle handles ID generation a little differently and I did not update the JPA mapping for this.
Click here to learn about my Spring Framework 5: Beginner to Guru Online Course!
A DataSource object is a factory for Connection objects. An object that implements the DataSource interface will typically be registered with a JNDI service provider. A JDBC driver that is accessed via the DataSource API does not automatically register itself with the DriverManager.
Constructor Summary
Spring Boot Properties
Configuring a different datasource in Spring Boot is very simple. When you supply datasource properties in Spring Boot’s application.properties file, Spring Boot will use them to configure the datasource. To configure Spring Boot for Oracle, add the following lines to your properties file.
Methods inherited from interface oracle.jdbc.datasource.OracleCommonDataSource
3.1 Datasources
The JDBC 2.0 extension API introduced the concept of datasources, which are standard, general-use objects for specifying databases or other resources to use. Datasources can optionally be bound to Java Naming and Directory Interface (JNDI) entities so that you can access databases by logical names, for convenience and portability.
This functionality is a more standard and versatile alternative to the connection functionality described under "Opening a Connection to a Database". The datasource facility provides a complete replacement for the previous JDBC DriverManager facility.
You can use both facilities in the same application, but ultimately we encourage you to transition your application to datasources. Eventually, Sun Microsystems will probably deprecate DriverManager and related classes and functionality.
For further introductory and general information about datasources and JNDI, refer to the Sun Microsystems specification for the JDBC 2.0 Optional Package.
Field Detail
DEFAULT_SERVICE_NAME
logWriter
loginTimeout
databaseName
serviceName
dataSourceName
description
networkProtocol
portNumber
password
serverName
driverType
tnsEntry
maxStatements
implicitCachingEnabled
explicitCachingEnabled
maxStatementsSet
implicitCachingEnabledSet
explicitCachingEnabledSet
odsCache
cacheManager
connCacheName
connCacheProperties
connectionProperties
connCachingEnabled
fastConnFailover
onsConfigStr
isOracleDataSource
driver
ENABLE_AC_SUPPORT_PROPERTY
TRACE
3.2.1 Database Specifiers
Table 3-2, "Oracle Extended Datasource Properties", shows the possible database specifiers, listing which JDBC drivers support each specifier.
Notes:
Oracle Service IDs are no longer supported at 10g Release 1 (10.1).
The Thin driver does not support Oracle Names.
Table 3-3 Supported Database Specifiers
OCI, using a cluster:
Notes:
-
For complete information on how to specify an Oracle Net connection descriptor, LDAP directory naming, or a TNS connection string, see the Oracle Net Services Administrator's Guide.
The Thin driver can use LDAP over SSL to communicate with Oracle Internet Directory if you substitute ldaps: for ldap: in the database specifier. The LDAP server must be configured to use SSL; if it is not, the connection attempt will hang.
3.2.1.1 Thin-style Service Name Syntax
Thin-style service names are supported only by the Thin driver. The syntax is:
@// host_name : port_number / service_name
Notes:
host_name can be the name of a single host or a cluster_alias .
The JDBC Thin driver supports only the TCP/IP protocol.
3.2.1.2 TNSNames Alias Syntax
You can find the available TNSNAMES entries listed in the file tnsnames.ora on the client computer from which you are connecting. On Windows, this file is located in the [ ORACLE_HOME ] \NETWORK\ADMIN directory. On UNIX systems, you can find it in the ORACLE_HOME directory or the directory indicated in your TNS_ADMIN environment variable.
For example, if you want to connect to the database on host myhost as user scott with password tiger that has a TNSNAMES entry of MyHostString , enter:
В современном мире без хранения данных никак. И история работы с базами данных началась уже очень давно, с появления JDBC. Предлагаю вспомнить то, без чего не обходися ни один современный фрэймворк, построенный поверх JDBC. Кроме того, даже работая с ними временами может понадобится возможность "вернуться к корням". Надеюсь, обзор поможет как вступительное слово или поможет что-то освежить в памяти.
Oracle Datasource
The easiest approach is to create a configuration bean in the package structure of your Spring Boot application. This will create a new Oracle datasource for your Spring Boot application. Once you specify a data source, Spring Boot will no longer create the H2 data source for you automatically.
Become a Spring Framework Guru!
3.1.3 Creating a Datasource Instance and Connecting (without JNDI)
This section shows an example of the most basic use of a datasource to connect to a database, without using JNDI functionality. Note that this requires vendor-specific, hard-coded property settings.
Create an OracleDataSource instance, initialize its connection properties as appropriate, and get a connection instance as in the following example:
Or optionally override the user name and password:
Constructor Detail
OracleDataSource
Spring Boot Advanced Configuration for Oracle
Spring Boot will set vendor specific properties using spring.datasource.. And you absolutely can go this route. However, based on my experience, it might be time to switch to a Java based configuration. Spring Boot will create the data source from just the properties file, or will forgo the automatic data source creation if you’re doing a more traditional method in Spring to define the data source bean.
In this section, I’m going to show you how to use a Spring configuration bean to create the Oracle JDBC datasource.
3.1.4 Creating a Datasource Instance, Registering with JNDI, and Connecting
This section exhibits JNDI functionality in using datasources to connect to a database. Vendor-specific, hard-coded property settings are required only in the portion of code that binds a datasource instance to a JNDI logical name. From that point onward, you can create portable code by using the logical name in creating datasources from which you will get your connection instances.
Note:
3.1.4.1 Initialize Connection Properties
Create an OracleDataSource instance, and then initialize its connection properties as appropriate, as in the following example:
3.1.4.2 Regi ster the Datasource
Once you have initialized the connection properties of the OracleDataSource instance ods , as shown in the preceding example, you can register this datasource instance with JNDI, as in the following example:
Calling the JNDI InitialContext() constructor creates a Java object that references the initial JNDI naming context. System properties that are not shown instruct JNDI which service provider to use.
The ctx.bind() call binds the OracleDataSource instance to a logical JNDI name. This means that anytime after the ctx.bind() call, you can use the logical name jdbc/sampledb in opening a connection to the database described by the properties of the OracleDataSource instance ods . The logical name jdbc/sampledb is logically bound to this database.
The JNDI name space has a hierarchy similar to that of a file system. In this example, the JNDI name specifies the subcontext jdbc under the root naming context and specifies the logical name sampledb within the jdbc subcontext.
The Context interface and InitialContext class are in the standard javax.naming package.
Notes:
3.1.4.3 Open a C onnection
To perform a lookup and open a connection to the database logically bound to the JNDI name, use the logical JNDI name. Doing this requires casting the lookup result (which is otherwise simply a Java Object ) to a new OracleDataSource instance and then using its getConnection() method to open the connection.
Here is an example:
Пример DBCP Apache Commons
Если вы посмотрите на приведенный выше класс фабрики источников данных Java, с ним связаны две основные проблемы.
- Методы заводского класса для создания источника данных MySQL и Oracle тесно связаны с соответствующим API драйверов. Если мы хотим удалить поддержку базы данных Oracle в будущем или хотим добавить какую-либо другую поддержку базы данных, это потребует изменения кода.
- Большая часть кода для получения источника данных MySQL и Oracle аналогична, единственное отличие-это класс реализации, который мы используем.
API Apache Commons DBCP помогает нам избавиться от этих проблем, предоставляя реализацию источника данных Java, которая работает как уровень абстракции между нашей программой и различными драйверами JDBC.
Библиотека Apache DBCP зависит от библиотеки общего пула, поэтому убедитесь, что они оба находятся в пути сборки, как показано на рисунке.
Вот класс фабрики источников данных, использующий BasicDataSource, который является простой реализацией источника данных.
Как вы можете видеть, в зависимости от пользовательского ввода создается либо источник данных MySQL, либо Oracle. Если вы поддерживаете только одну базу данных в приложении, то вам даже не нужна эта логика. Просто измените свойства, и вы сможете переключаться с одного сервера базы данных на другой. Ключевым моментом, с помощью которого Apache DBCP обеспечивает абстракцию, является setDriverClassName() метод.
Вот клиентская программа, использующая вышеуказанный заводской метод для получения различных типов соединений.
Когда вы запустите вышеуказанную программу, результат будет таким же, как и в предыдущей программе.
Если вы посмотрите на источник данных Java JDBC и выше, это можно сделать и с помощью обычного DriverManager. Основное преимущество источника данных Java заключается в том, что он используется в контексте и с JNDI.
С помощью простых конфигураций мы можем создать пул подключений к базе данных, который поддерживается самим контейнером. Большинство контейнеров сервлетов, таких как Tomcat и JBoss, предоставляют собственную реализацию источника данных Java, и все, что нам нужно, – это настроить его с помощью простых конфигураций на основе XML, а затем использовать контекстный поиск JNDI для получения источника данных Java и работы с ним. Это помогает нам, заботясь о пуле соединений и управлении ими со стороны нашего приложения на сторону сервера, и, таким образом, дает нам больше времени для написания бизнес-логики для приложения.
В следующем уроке мы узнаем, как настроить источник данных в контейнере Tomcat и использовать его в веб-приложении.
Читайте также: