For some cases you want the actual DataSource available as a service in OSGi. Most tutorials show how to do this using blueprint to create a DataSource and publish it as a service. The problem with this approach is that you have to create and deploy a blueprint file for each DataSource and the blueprint is also Database specific.
The bundle pax-jdbc-config follows a different approach. It creates and publishes a DataSource and a XADataSource from a config with the help of an existing DataSourceFactory service. Simply install the necessary bundles and create a config with the factory pid org.ops4j.datasource. In Apache Karaf this means to create a config with a name like etc/org.ops4j.datasource-*.cfg.
The created DataSource will also be given the osgi.jndi.service.name property. So if aries jndi is present it will automatically be available using jndi. So it can be used in a persistence.xml.
|osgi.jdbc.driver.name||Identify the DataSourceFactory by name|
|osgi.jdbc.driver.class||Identify the DataSourceFactory by class|
|dataSourceName||Will be set as dataSourceName as well as osgi.jndi.service.name in the published service|
|ops4j.preHook||1.1.0||Name of a PreHook service to call before the DataSource is published. Such a service must implement org.ops4j.pax.jdbc.hook.PreHook and have a service property name with the same value as this config property.|
All other local properties (not containing a dot) are forwarded to the DataSourceFactory to create the DataSource. Additionally, properties prefixed with "jdbc." will also be forwarded, the prefix being discarded.
For instance "username" will be forwarded, but "aries.xa.name" will not be forwarded to the DataSourceFactory (but published as service properties in the service registry).
Properties are also published as service properties in the service registry. Hidden properties are supported (starting with a dot, e. g. ".password"). Such properties are not shown in the service registry, however, they are forwared to the DataSourceFactory (without the leading dot).
Installation in karaf 3/4
Create config in etc/org.ops4j.datasource-test.cfg:
Install the features
feature:install pax-jdbc-h2 pax-jdbc-config
The automatically created DataSource service will look like this:
karaf@root()> service:list javax.sql.DataSource
dataSourceName = test2
service.factoryPid = org.ops4j.datasource
databaseName = test
user = sa
osgi.jdbc.driver.name = H2
osgi.jndi.service.name = test2
felix.fileinstall.filename = file:/.../etc/org.ops4j.datasource-test2.cfg
service.pid = org.ops4j.datasource.b1809982-d20a-4b84-b48c-ad23bbafb9ec
service.id = 679
Provided by :
OPS4J Pax JDBC Config (72)
The service is identified by the given dataSourceName. So you can filter for it with (&(objectClass=javax.sql.DataSource)(dataSourceName=test2)).
The dataSource can be referenced from a persistence.xml using: