- Create a Fuse project (archtype contract first) and name it Datasource - this is the Datasource project which will be deployed independently
- In the blueprint.xml add the code below
<cm:property-placeholder persistent-id="configuration" update-strategy="reload" /> <bean id="dbcp" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.ibm.db2.jcc.DB2Driver"/> <property name="url" value="${db.jdbc.url}"/> <property name="username" value="${db.jdbc.username}"/> <property name="password" value="${db.jdbc.password}"/> </bean> <service interface="javax.sql.DataSource" ref="dbcp"> <service-properties> <entry key="osgi.jndi.service.name" value="jdbc/DBDS"/> <entry key="datasource.name" value="DBDS"/> </service-properties> </service>
- Configuration - this needs to be saved as configuration.cfg and places under <installs-dir>/etc
db.datasource=DBDS db.jndi.datasource=jdbc/DBDS db.jdbc.username=abcd db.jdbc.password=abcd db.jdbc.url=jdbc:db2://<ip-address>:<port>/<databasename>
- Dependency to be added in pom.xml
<modelVersion>4.0.0</modelVersion> <groupId>com.test.ds</groupId> <artifactId>datasource</artifactId> <name>DataSource</name> <version>1.0.0-SNAPSHOT</version> <packaging>bundle</packaging> <dependencies> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> </dependencies>
- Once the Datasource project is ready the Datasource object can be used in beans across several projects
- Create a new Fuse project - name it TestDB (archtype - contract first)
- In the blueprint add the code below
<bean id="SomeBean" class="com.some.bean.SomeBean"> <property name="dataSource"> <reference filter="(datasource.name=DBDS)" interface="javax.sql.DataSource" /> </property> </bean>
- the datasource name is registered as "DBDS" - and this is referred from the bean "SomeBean"
public class SomeBean{
private DataSource dataSource = null;
public DataSource getDataSource() { return dataSource; } public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } public String testDBConnection() { //in this bean u can access the datasource and get connection DataSource ds = getDataSource(); if(ds != null) { Connection conn = ds.getConnection() } } }
- Once the datasource is accessable from a bean - life is simple and we can do any kind of DB queries
- While testing in JBoss Fuse - please install features mentioned below
- osgi:install wrap:mvn:commons-dbcp/commons-dbcp/1.4