First we need to add spring-boot-starter-parent as parent under project. It is used for default configuration of the components
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
@RestController
public class HelloController {
@RequestMapping("/hello")
public String index() {
return "Greetings";
}
}
Lets initialize spring boot application by creating a class in same package called Application.java, can be any name but need to have @SpringBootApplicaation annotation. Here we can configure all the controller classes by passing it as an array of object
@SpringBootApplication
public class Application {
public static void main(String[] args){
Object[] obj = {Application.class,HelloController.class};
SpringApplication.run(obj, args);
}
}
Now lets connect to MySQL server. In this example we are gettng the user name from user table by user id and display the greetings
Lets revisit pom.xml and add dependencies related to JDBC and MySQL
Add JDBC and MySQL dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
@RestController
public class HelloController {
@Autowired
private JdbcTemplate jdbcTemplate;
@RequestMapping("/hello")
public String index(){
DataSource ds = jdbcTemplate.getDataSource();
Connection con = null;
String s = null;
try {
con = ds.getConnection();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(" select first_name from t_user_main where user_id = 1 ");
while(rs.next()) {
s = rs.getString(1);
System.out.println(s);
}
} catch (SQLException e) {
e.printStackTrace();
}
return "Greetings "+s;
}
}
server.port=5000
Example
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://awsdbinstance.xxxxxx.us-west-2.rds.amazonaws.com:3306/default
spring.datasource.username=awsuser
spring.datasource.password=awsuserpassword