使用Spring Boot连接到MySQL的代码片段
环境
春季工具套件4.3.2
XAMPP 3.2.4
简要说明
・第一次发布。主要是为了自己而在Qjita上保存起来。
・我正在尝试使用Angular和Spring Boot来搭建Web应用开发环境,遇到了许多困难。
・由于无论如何都无法解决JPA的问题,我决定使用JDBC进行连接。
写作方式
将源代码添加到application.properties文件中。
?之前是数据库名称。因为出现了不存在时区的错误,
所以我写下了serverTimezone=JST以解决这个问题。
spring.datasource.url=jdbc:mysql://localhost:3306/example?serverTimezone=JST
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
依赖性的设定 de
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
在列表中指定SQL语句
package com.example.demo;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(path="/jdbc/sample")
public class DbController {
@Autowired
JdbcTemplate jdbcTemplate;
@RequestMapping(path="/users", method=RequestMethod.GET)
public String index() {
List<Map<String,Object>> list;
list = jdbcTemplate.queryForList("select * from heroes");
return list.toString();
}
@RequestMapping(path="/users/{id}", method=RequestMethod.GET)
public String read(@PathVariable String id) {
List<Map<String,Object>> list;
list = jdbcTemplate.queryForList("select * from users where id = ?", id);
return list.toString();
}
}
下一次
角度⇔Spring Boot⇔数据库(MySQL)