Sunday, April 18, 2010

Calling Non-spring code from Spring

Given below is an example of how to manage connections when calling non-Spring code. Remember to close connection retrieved since Spring will not manage it. You may use extends SimpleJdbsDaoSupport for the class as well and then use the connection retrieved from existing pool. But jdbcTemplate.getDataSource().getConnection() and dataSource.getConnection() are create a brand new connection.

@Service
public class BomImpl {

@Autowired
private DataSource dataSource;

@Transactional(readOnly = true, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void functionName(Recipe recipe) throws Exception {

Connection conn = null;
try {
//conn = jdbcTemplate.getDataSource().getConnection();
//this will return a brand new connection instead of existing one.
conn = DataSourceUtils.getConnection(this.dataSource); //this is the right way to grab the current connection
refDesResult = instance.getRefDesList(conn,
recipe.getOrder().getBusinessUnit(), item, recipe
      .getOrder().getNewStartDate(), "PR", "PR", 99);
} finally {
      if (conn != null) {
            DataSourceUtils.releaseConnection(conn, this.dataSource);
}
}//finally

}//functionName


}//class

No comments:

Post a Comment

Thank you for your feedback