Wednesday, February 2, 2011

Connecting to a database with Napalm

In line with our ideas of instant web gratification, Napalm offers a super simple way of connecting to a JDBC datasource and exposing it as a Spring bean.

Just do this something like this:

Napalm.addResource("db", "jdbc:h2:mem:db1");
Napalm.run(8080,MyApp.class);

And in your app you get a nice Apache Commons DBCP data source created for you automatically:

@Resource(name = "db")
private DataSource db;

No more fiddling with JNDI. You can also pass the user name/password in the same string, delimited by a comma, e.g.

Napalm.addResource("db", "jdbc:mysql://localhost:3306/napalm,user,password");
Napalm.run(8080,MyApp.class);

Just one of the ways Napalm tries to minimize the time from thinking about your app to actually running it.

Full example below:

@Service
@Path("/")
@Produces(MediaType.TEXT_PLAIN)
public class NapalmTestApp {

        @Resource(name = "db")
        private DataSource db;

        @GET @Path("/db")
        public String getDbInfo() {
                return String.valueOf(new JdbcTemplate(db).queryForInt("SELECT COUNT(*) FROM INFORMATION_SCHEMA.CATALOGS"));
        }

        public static void main(String[] args) {
                Napalm.addResource("db", "jdbc:h2:mem:db1");
                Napalm.run(8080, NapalmTestApp.class);
        }
}
}