4

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?

2 Answers 2

5

Looks like your missing the database name, for example the database named test:

spring.datasource.url=jdbc:mysql://localhost:3306/test

Hope it helps

Sign up to request clarification or add additional context in comments.

1 Comment

When I do that I get an error because: "Communications link failure", how do I use a mysql docker container in Springboot, is it an other url because I am on windows?
4

The problem that you are facing is because you aren't providing the database name, you can't do a query for a whole server therefore.

Wrong format:

spring.datasource.url=jdbc:mysql://localhost:3306

Right Format:

spring.datasource.url=jdbc:mysql://localhost:3306/accounts

The general format is like this

jdbc:[Database Type]://[Host Resolver]:[Port]/[Database Name]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.