Accessing databases in servicemix-drools

ServiceMix provides a Service Engine for Drools, the famous Rules Engine.

People often want to retrieve data from the rules and such data is usually stored in a database. Previously there was no easy way to configure a DataSource and inject it in the rules definitions. This is a small enhancement that I've just written and that will be included in next major release.

So let's say you write your database access code in a simple helper object:
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;

public class DbHelper {
private DataSource dataSource;
private JdbcTemplate jdbcTemplate;

public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplate = new JdbcTemplate(dataSource);

public String getSurname(String name) {
String surname = (String) this.jdbcTemplate
"select surname from t_actor where name = ?",
new Object[]{name}, String.class);

Now, let's use it in our rule definition:
import org.apache.servicemix.drools.model.Exchange;
global org.apache.servicemix.drools.model.JbiHelper jbi;
global DbHelper helper;

rule Init
$me : Exchange()
String t = $me.getIn().getContent().getTextContent();
+ helper.getSurname(t)
+ "</surname>");

And the xbean.xml would look like:
<drools:endpoint  service="test:service"
globals="#globals" />
<util:map id="globals">
<entry key="helper" value-ref="helper" />
<bean id="helper" class="DbHelper">
<property name="dataSource">
<bean class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:myDataBase" />

This will make available the helper bean to the rules while initializing it with a DataSource looked up from JNDI.

Happy hacking !


Popular posts from this blog

Apache Karaf

Camel Endpoint DSL

ActiveMQ Pooling