14
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Spring bootでMySQL接続

Posted at

#環境
Spring tool suite 4.3.2
XAMPP 3.2.4

#摘要
・初投稿。主に自分用にQjitaに残していく。
・Angular と Spring bootでWeb applicattion開発環境を整えようと四苦八苦してます。
・JPAは何度やってもハマったので、JDBCで接続。

#書き方
application.propertiesにソースを追加する。
?の前がデータベース名。Timezoneが存在しないというエラーが出たので、
serverTimezone=JSTと記載して突破できた。

application.propreties
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

依存性の指定

pom.xml
	<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>

list内でsql文を指定している

DbController.java
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();
   }
}

#次回
angular⇔spring boot⇔データベース(MySQL)

14
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?