1、pom文件:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
注意:mysql版本号,否则可能因为版本号不支持导致报错
2、application.properties
# mysql
spring.datasource.url= jdbc:mysql://127.0.0.1:3306/data?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
spring.datasource.username= root
spring.datasource.password= 000
spring.datasource.driver-class-name = com.mysql.jdbc.Driver
注意:1、url可能会报编码错误和时区问题,可利用上述url解决
2、mysql的用户名变量是 username 而非 name
3、controller
package com.helloworlds.example.rest.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
@Controller
public class User {
@Autowired
private JdbcTemplate jdbcTemplate;
@RequestMapping(value = "/getUsers",method = RequestMethod.GET)
@ResponseBody
/*
* List 里的对象是Map对象,而Map对象是
* 由一个String类型的键和Object类型的值组成
* */
public List<Map<String,Object>> getUsers(){
String sql="select * from user";//SQL查询语句
List<Map<String,Object>> list=jdbcTemplate.queryForList(sql);
return list;
}
}
4、请求: