Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 749
Chris Bolton Avatar asked Jan 04 '23 13:01

Chris Bolton


2 Answers

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

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

Hope it helps

like image 166
Jorge Chavez Avatar answered Jan 06 '23 01:01

Jorge Chavez


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]

like image 28
CptPackage Avatar answered Jan 06 '23 03:01

CptPackage