How do I create a Data Source object for JdbcTemplate?

In this example you will learn how to create and configure a DriverManagerDataSource object that will be used by the JdbcTemplate object. There are some information required when creating a DataSource including the JDBC driver class, the JDBC Url of the target database, the username and password for connecting to database server.

package org.kodejava.example.spring.jdbc;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;
import java.util.List;

public class DataSourceDemo {
    public static final String DRIVER = "com.mysql.jdbc.Driver";
    public static final String JDBC_URL = "jdbc:mysql://localhost/mediadb";
    public static final String USERNAME = "root";
    public static final String PASSWORD = "";

    public static void main(String[] args) {
        // Creates an instance of DriverManagerDataSource and pass
        // it to the JdbcTemplate.
        DataSource source = getDataSource();
        JdbcTemplate template = new JdbcTemplate(source);

        // After creating a template with a data source inject we
        // can do a database manipulation such as the CRUD operation.
        System.out.println("DataSource = " + template.getDataSource());
        List records = template.queryForList("SELECT * FROM records");
        for (int i = 0; i < records.size(); i++) {
            System.out.println("Records = " + records.get(i));
        }
    }

    /**
     * Returns a DataSource object for connection to the database.
     *
     * @return a DataSource.
     */
    private static DataSource getDataSource() {
        // Creates a new instance of DriverManagerDataSource and sets
        // the required parameters such as the Jdbc Driver class,
        // Jdbc URL, database user name and password.
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(DataSourceDemo.DRIVER);
        dataSource.setUrl(DataSourceDemo.JDBC_URL);
        dataSource.setUsername(DataSourceDemo.USERNAME);
        dataSource.setPassword(DataSourceDemo.PASSWORD);
        return dataSource;
    }
}

How do I insert a new record into a database using JdbcTemplate?

The following example show you how to use the Spring’s JdbcTemplate class to insert a record into database.

package org.kodejava.example.spring.jdbc;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;
import java.sql.Types;
import java.util.Date;

public class InsertDemo {
    private static final String sql =
            "INSERT INTO records (title, " +
            "    release_date, " +
            "    artist_id, " +
            "    label_id, " +
            "    created) " +
            "VALUES (?, ?, ?, ?, ?)";

    private DataSource dataSource;

    public InsertDemo(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public void saveRecord(String title, Date releaseDate,
                           Integer artistId, Integer labelId) {
        //
        // Creates an instance of JdbcTemplate and passes a connection
        // to the database.
        //
        JdbcTemplate template = new JdbcTemplate(this.dataSource);

        //
        // Defines the query arguments and the corresponding SQL types
        // of the arguments.
        //
        Object[] params = new Object[] {
                title, releaseDate, artistId, labelId, new Date()
        };
        int[] types = new int[] {
                Types.VARCHAR,
                Types.DATE,
                Types.INTEGER,
                Types.INTEGER,
                Types.DATE
        };

        //
        // Calls JdbcTemplate.update() methods to create a new data
        // in the records table. The update method in general will
        // return number of row / rows processed by the executed query
        //
        int row = template.update(sql, params, types);
        System.out.println(row + " row inserted.");
    }

    public static DriverManagerDataSource getDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost/mediadb");
        dataSource.setUsername("root");
        dataSource.setPassword("");
        return dataSource;
    }

    public static void main(String[] args) {
        DataSource dataSource = getDataSource();

        InsertDemo demo = new InsertDemo(dataSource);
        demo.saveRecord("Rock Beatles", new Date(), 1, 1);
    }
}