好家伙,
這里使用的軟件是IDEA 2021
1.新建項目
2.更改配置項目文件目錄
更改前:
更改后:
2.1.更改pom.xml文件
在該文件中添加:
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency>
2.2.更改配置application.properties文件
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test //按你說的數據庫名字改 spring.datasource.username=root //按你的的數據庫用戶名改,一般都是'root' spring.datasource.password=root //按你的的數據庫密碼改 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.max-idle=10 spring.datasource.max-wait=10000 spring.datasource.min-idle=5 spring.datasource.initial-size=5 server.port=8011 server.session.timeout=10 server.tomcat.uri-encoding=UTF-8
2.3.更改配置TestController文件:
代碼如下:

package com.example.demo.controller; //按文件的實際路徑來寫
import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; 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.RestController; @RestController @RequestMapping("/mydb") public class TestController { @Autowired private JdbcTemplate jdbcTemplate; @RequestMapping("/getUsers") public List<Map<String, Object>> getDbType(){ String sql = "select * from appuser"; List<Map<String, Object>> list = jdbcTemplate.queryForList(sql); for (Map<String, Object> map : list) { Set<Entry<String, Object>> entries = map.entrySet( ); if(entries != null) { Iterator<Entry<String, Object>> iterator = entries.iterator( ); while(iterator.hasNext( )) { Entry<String, Object> entry =(Entry<String, Object>) iterator.next( ); Object key = entry.getKey( ); Object value = entry.getValue(); System.out.println(key+":"+value); } } } return list; } @RequestMapping("/user/{id}") public Map<String,Object> getUser(@PathVariable String id){ Map<String,Object> map = null; List<Map<String, Object>> list = getDbType(); for (Map<String, Object> dbmap : list) { Set<String> set = dbmap.keySet(); for (String key : set) { if(key.equals("id")){ if(dbmap.get(key).equals(id)){ map = dbmap; } } } } if(map==null) map = list.get(0); return map; } }
2.4.更改配置主啟動程序DemoApplication文件
代碼如下:
package com.example.demo; //按文件的實際路徑來寫
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
3.mysql新建表
spring boot這邊基本上搞定了,
前往mysql workbench
3.1.添加一個名為appuser的表
並在其中設置'id','name','password'等屬性
中填一點數據用於測試
4.前往spring boot 中啟動主程序
啟動主程序DemoApplication
點擊進入localhost:8011/mydb/getUsers
不出意外的話,應該是出不了什么意外了
搞定!!
That's all