Spring JDBC application on WildFly

User Rating: 4 / 5

Star ActiveStar ActiveStar ActiveStar ActiveStar Inactive

This tutorial demonstrates how to develop a Web application using PrimeFaces for the User Interfaces, Spring JDBC for handling persistence and CDI as glue between these technologies. 

Although there are many technologies in this tutorial, you will see that mixing them is not complicated at all. You need a basic Web project as startup; for example the webapp-javaee7 can fit this purpose:

mvn -DarchetypeGroupId=org.codehaus.mojo.archetypes
-Darchetype.interactive=false --batch-mode --update-snapshots archetype:generate

The first class that we will add is a CDI Bean which is in charge to produce and dispose the ConfigurableApplicationContext:

public class SpringProducer {
        public ConfigurableApplicationContext create() {
            return new ClassPathXmlApplicationContext("applicationContext.xml");

        public void close(@Disposes final ConfigurableApplicationContext ctx) {

The  ConfigurableApplicationContext is a provider interface which is used to provide an application context to Spring application, by loading beans definition into the file applicationContext.xml

Here is the applicationContext.xml file which defines a Spring Bean named jdbcCustomerDAO and a datasource that is retrieved from the JNDI at "java:jboss/datasources/ExampleDS" (This is the default H2 database included in JBoss/WildFly distribution):

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsdhttp://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.2.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.2.xsdhttp://www.springframework.org/schema/jeehttp://www.springframework.org/schema/jee/spring-jee-3.2.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.2.xsdhttp://www.springframework.org/schema/taskhttp://www.springframework.org/schema/task/spring-task-3.2.xsd">
    <bean id="jdbcCustomerDAO" class="mastertheboss.dao.JDBCCustomerDAOImpl">
        <property name="dataSource" ref="dataSource" />
    <jee:jndi-lookup id="dataSource" jndi-name="java:jboss/datasources/ExampleDS"/>

Let's see the definition of the class JDBCCustomerDAOImpl:

public class JDBCCustomerDAOImpl implements JDBCCustomerDAO {
    private DataSource dataSource;
    private JdbcTemplate jdbcTemplate;

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

    public void createTable() {
        jdbcTemplate = new JdbcTemplate(dataSource);
                .execute("create table customer (name varchar, surname varchar, age integer)");

    public void dropTable() {
        jdbcTemplate = new JdbcTemplate(dataSource);
        jdbcTemplate.execute("drop table customer");

    public void insert(Customer customer) {

        String sql = "INSERT INTO CUSTOMER "
                + "(NAME,SURNAME, AGE) VALUES (?, ?, ?)";

        jdbcTemplate = new JdbcTemplate(dataSource);

                new Object[] { customer.getName(), customer.getSurname(),
                        customer.getAge() });

    public List<Customer> findAll() {

        jdbcTemplate = new JdbcTemplate(dataSource);
        String sql = "SELECT * FROM CUSTOMER";

        List<Customer> customers = new ArrayList<Customer>();

        List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql);
        for (Map row : rows) {
            Customer customer = new Customer();
            customer.setSurname((String) row.get("SURNAME"));
            customer.setName((String) row.get("NAME"));

        return customers;


As you can see, this class uses Spring JDBC template API for handling database persistence, which is an alternative to plain JDBC (where you have to code by yourself all the JDBC creation/disposal layer) and to JPA/Hibernate where Database table and fields are represented as Java types.

When using Spring JDBCTemplate, the mapping is handled by implementing the RowMapper interface and the mapRow method, which receives as input the single record as a ResultSet and returns a generic Object type:

public class CustomerRowMapper implements RowMapper    {
        public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
            Customer customer = new Customer();
            return customer;

The Customer class which is referenced, contains the fields that are arriving from the UI and uses the DAO class for inserting and retrieving the list of Customers:

public class Customer {
    ConfigurableApplicationContext context;
    private String name;
    private String surname;
    private int age;

    public Customer() { }

    public Customer(String name, String surname, int age) {
        this.name = name;
        this.surname = surname;
        this.age = age;

    public String getSurname() {
        return surname;

    public void setSurname(String surname) {
        this.surname = surname;

    public String getName() {
        return name;

    public void setName(String name) {
        this.name = name;

    public int getAge() {
        return age;

    public void setAge(int age) {
        this.age = age;

    public void insertCustomer() {
        JDBCCustomerDAO dao = (JDBCCustomerDAO) context
        Customer emplNew = new Customer(name, surname, age);


    List<Customer> customerList;

    public void setCustomerList(List<Customer> customerList) {
        this.customerList = customerList;

    public List<Customer> getCustomerList() {
        JDBCCustomerDAO jdbcEmployeeDAO = (JDBCCustomerDAO) context

        this.customerList = jdbcEmployeeDAO.findAll();
        return customerList;

That's all! easy-peasy! The last class I've included is a ContextListener that is used for creating and dropping the table used after each deployment (I do accept suggestions and tips to improve this approach):

public class MyContextListener implements ServletContextListener {
    ConfigurableApplicationContext context;

    public void contextInitialized(ServletContextEvent sce) {
        JDBCCustomerDAO dao = (JDBCCustomerDAO) context



    public void contextDestroyed(ServletContextEvent sce) {
        JDBCCustomerDAO dao = (JDBCCustomerDAO) context



This application has a Primefaces front-end that contains an upper panel for inserting a Customer and a tabular list of data in the lower panel:

<!DOCTYPE html>
<html xmlns="http://www.w3c.org/1999/xhtml"


    <h:form id="jsfexample">
        <p:panelGrid columns="2">
            <f:facet name="header">Enter Customer</f:facet>
            <h:outputText value="Name" />
            <h:inputText value="#{customer.name}" />

            <h:outputText value="Surname" />
            <h:inputText value="#{customer.surname}" />

            <h:outputText value="Age" />
            <h:inputText value="#{customer.age}" />
            <f:facet name="footer">
                <h:commandButton actionListener="#{customer.insertCustomer}"
                    styleClass="buttons" value="Insert Customer" />

    <br />
    <h:outputText value="Customer List" />
    <br />
    <p:dataTable var="c" value="#{customer.customerList}">

        <p:column headerText="Name">
            <h:outputText value="#{c.name}" />

        <p:column headerText="Surname">
            <h:outputText value="#{c.surname}" />
        <p:column headerText="Age">
            <h:outputText value="#{c.age}" />



Here is how the application looks like when running:

spring wildfly jdbc tutorial

That's all. You can download the Maven project from here. In the next tutorial we will show how to install Spring as a module on WildFly. Stay tuned!