修改pom.xml
新增tag数据表
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for tags
-- ----------------------------
DROP TABLE IF EXISTS `tags`;
CREATE TABLE `tags` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of tags
-- ----------------------------
INSERT INTO `tags` VALUES ('14', 'java');
INSERT INTO `tags` VALUES ('15', 'javascript');
INSERT INTO `tags` VALUES ('16', 'python');
INSERT INTO `tags` VALUES ('17', 'golang');
INSERT INTO `tags` VALUES ('18', 'php');
INSERT INTO `tags` VALUES ('19', 'dfdsfsd');
INSERT INTO `tags` VALUES ('20', 'fafdaf');
INSERT INTO `tags` VALUES ('21', 'zzzzzz');
src/main下新增resources目录
resources目录下新增application.yml
server:
port: 8008
spring:
profiles:
active: dev
resources目录下新增application-dev.yml
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: root
url: jdbc:mysql://localhost:3307/my_realworld?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&useSSL=false
type: com.zaxxer.hikari.HikariDataSource
新增以下包和文件
Tag.java
package org.example.domain;
import lombok.Data;
@Data
public class Tag {
private Long id;
private String name;
}
TagRsp.java
package org.example.domain;
import java.util.List;
public class TagRsp {
public List<String> tags;
}
TagMapper.java
package org.example.mapper;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface TagMapper {
@ResultType(String.class)
@Select("select name from tags")
List<String> allTags();
}
TagController.java
package org.example.controller;
import org.example.domain.TagRsp;
import org.example.mapper.TagMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("api")
public class TagController {
private final TagMapper tagMapper;
@Autowired
public TagController(TagMapper tagMapper) {
this.tagMapper = tagMapper;
}
@GetMapping("/tags")
public ResponseEntity<?> getTags() {
TagRsp tagRsp = new TagRsp();
tagRsp.tags = tagMapper.allTags();
return ResponseEntity.status(HttpStatus.OK).body(tagRsp);
}
}