Running Spring JDBC Application

Here is a demo code of how all this can be put together.
Create a package com.cosmiclearn.galaxyexplorer and add the following code.

package com.cosmiclearn.galaxyexplorer;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.jdbc.core.JdbcTemplate;

import com.cosmiclearn.model.CosmicObject;

@SpringBootApplication
@ComponentScan({"com.cosmiclearn.controller"})
public class GalaxyExplorerApplication 
				implements CommandLineRunner
{
	@Autowired
	JdbcTemplate jdbcTemplate;
	
	public static void main(String[] args) 
	{
		SpringApplication.run(GalaxyExplorerApplication.class, args);
	}

	@Override
	public void run(String... args) throws Exception 
	{	
		System.out.println("Starting JDBC Demo");
		
		// Creating table in database.
		jdbcTemplate.execute("CREATE TABLE COSMICOBJECT(NAME VARCHAR(100), " + 
					"GALAXYNAME VARCHAR(100)," +
					"WEIGHT INT, " + 
					"NUMBEROFEARTHYEARS INT)");
		
		System.out.println("Created Table in Database");
		
		List<CosmicObject> cosmicObjectList 
			= new ArrayList<CosmicObject>();
		
		// Get sample data ready for CosmicObject
		cosmicObjectList.add(new CosmicObject("Earth", "Milky Way",
							10000, 1));
		cosmicObjectList.add(new CosmicObject("Zanibar", "Andromeda",
							4000, 4));
		for(CosmicObject cosmicObject: cosmicObjectList)
		{
			jdbcTemplate.update("INSERT INTO COSMICOBJECT(NAME, GALAXYNAME, WEIGHT, NUMBEROFEARTHYEARS) " + " VALUES (?, ?, ?, ?)", cosmicObject.getName(), cosmicObject.getGalaxy(),
					cosmicObject.getWeight(), cosmicObject.getNumberOfEarthYears());
		}
		
		System.out.println("Inserted data into COSMICOBJECT table");
		
		System.out.println("Getting data from COSMICOBJECT table");
		
		jdbcTemplate.query("SELECT NAME, GALAXYNAME, WEIGHT, NUMBEROFEARTHYEARS FROM COSMICOBJECT WHERE " +  
				"NAME = ?", new Object[]{"Earth"},
				(resultSet, rowNumber) -> new CosmicObject(resultSet.getString("name"),
				resultSet.getString("galaxyname"),
				resultSet.getInt("weight"),
				resultSet.getInt("numberOfEarthYears")))
			.forEach(cosmicObject -> System.out.println("CosmicObject Name = "
				+ cosmicObject.getName() + 
				", Galaxy Name = " + 
				cosmicObject.getGalaxy())
				);
	}
}

As you can see above, we implemented the CommandLineRunner interface, which will enable the run method to be called.

Output:
Starting JDBC Demo
Created Table in Database
Inserted data into COSMICOBJECT table
Getting data from COSMICOBJECT table
CosmicObject Name = Earth, Galaxy Name = Milky Way

Previous: Querying Table

<