一 开发准备 mysql 建表。
CREATE TABLE `users` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(20) DEFAULT NULL,
`age` INT DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb3
二 创建项目 ,跑个hello world 出来。
创springboot 项目 , 注意选择以下依赖.
再追加一个gson .
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
实现一个控制器。
package tech.xuxing.d11.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@GetMapping("/test")
public String test()
{
return "hello world";
}
}
三 配数据库连接。 采用yml (springboot 官方推荐)
注意排坑 mysql8 要加allowPublicKeyRetrieval=true
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&allowPublicKeyRetrieval=true
username: root
password: xuxing
driver-class-name: com.mysql.cj.jdbc.Driver
name: default
四 写pojo ,dao 层(mapper) 进行测试。
实体类。 用了Lombok 代码清爽好多。
package tech.xuxing.d11.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
@Data
@AllArgsConstructor
@Getter
@Setter
public class Users {
private int id;
private String name;
private int age;
}
dao 层 mapper 类。
package tech.xuxing.d11.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Component;
import tech.xuxing.d11.pojo.Users;
import java.util.List;
@Mapper
@Component
public interface UserMapper {
@Select("select * from users")
List<Users> findAll();
}
真实业务会有一层 service 层,这里仅展示基础实现,略掉
进行测试 。
package tech.xuxing.d11;
import com.google.gson.Gson;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import tech.xuxing.d11.mapper.UserMapper;
import tech.xuxing.d11.pojo.Users;
import java.util.List;
@SpringBootTest
class D11ApplicationTests {
@Autowired
UserMapper uMapper;
@Test
void contextLoads() {
Gson gson = new Gson();
List<Users> users = uMapper.findAll();
System.out.println(gson.toJson(users));
}
}
最后,整合进控制器层。
package tech.xuxing.d11;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class D11Application {
public static void main(String[] args) {
SpringApplication.run(D11Application.class, args);
}
}
最后: mapper 还可以基于xml 去配置。(觉得恶心麻烦,实现屁大的事,要到处折腾,就跳过了)