Categories
database-connection java mysql spring-boot

Spring Boot Connect to mysql docker

I have spun up the mysql docker image.

From docker ps:

bcb0a900b693 mysql:latest "docker-entrypoint..." 5 hours ago Up About an hour 0.0.0.0:3306->3306/tcp chrisbolton

I have created a basic spring boot project where I have created a simple class.

@SpringBootApplication
@RestController
public class ChrisboltonServiceApplication {
public static void main(String[] args) {
SpringApplication.run(ChrisboltonServiceApplication.class, args);
}
@Autowired
private JdbcTemplate jdbcTemplate;
@RequestMapping("/hello")
public String sayHello(){
return "Hello";
}
@RequestMapping(path="/blogs")
public @ResponseBody Iterable<ChrisBolton> getAllUsers() {
List<ChrisBolton> result = jdbcTemplate.query(
"SELECT * FROM blog",
(rs, rowNum) -> new ChrisBolton(rs.getString("author"),
rs.getString("title"),
rs.getString("content"),
rs.getDate("date"))
);
return result;
}

}

I have placed my configuration in my application.properties

spring.main.banner-mode=off
spring.datasource.url=jdbc:mysql://localhost:3306
spring.datasource.username=root
spring.datasource.password=opening
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

When I start my app, I am able to hit localhost:8080/hello which returns Hello!

When I hit localhost:8080/blogs, I get this error

java.sql.SQLException: No database selected

So I guess I don’t understand how the autowired is completely working.

I have tried looking into beans or maybe using the Connection class. But what is the correct Spring Boot way of connecting to my mysql instance?