简体   繁体   中英

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?

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

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

Hope it helps

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM