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.
Properties
Key | Description |
---|---|
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 |
* | All other properties are forwarded to the DataSourceFactory to create the DataSource |
Installation in karaf 3
Create config in etc/org.ops4j.datasource-test.cfg:
osgi.jdbc.driver.name=H2 databaseName=test user=sa password= dataSourceName=testds-h2
Install the features
feature:repo-add mvn:org.ops4j.pax.jdbc/pax-jdbc-features/0.8.0/xml/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 [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 password = service.id = 679 Provided by : OPS4J Pax JDBC Config (72)
Usage
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:
<non-jta-data-source>osgi:service/javax.sql.DataSource/(osgi.jndi.service.name=test2)</non-jta-data-source>