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:
Now, let's use it in our rule definition:
And the xbean.xml would look like:
This will make available the
Happy hacking !
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);
this.jdbcTemplate.afterPropertiesSet();
}
public String getSurname(String name) {
String surname = (String) this.jdbcTemplate
.queryForObject(
"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
when
$me : Exchange()
then
String t = $me.getIn().getContent().getTextContent();
jbi.answer("<surname>"
+ helper.getSurname(t)
+ "</surname>");
end
And the xbean.xml would look like:
<drools:endpoint service="test:service"
endpoint="endpoint"
ruleBaseResource="classpath:router.drl"
globals="#globals" />
<util:map id="globals">
<entry key="helper" value-ref="helper" />
</util:map>
<bean id="helper" class="DbHelper">
<property name="dataSource">
<bean class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:myDataBase" />
</bean>
</property>
</bean>
This will make available the
helper
bean to the rules while initializing it with a DataSource looked up from JNDI.Happy hacking !
Comments