实现第一个API
写下自己的第一个API
最终成果:https://159.75.105.236:5888/user/all
相关工具及准备
1.自己去买一个服务器,腾讯云、阿里云都可以,直接安装宝塔(额外安装:java项目一键部署)
2.IntelliJ + spring-boot
至少添加这部分依赖
3.mysql数据库
自行完成数据库的搭建。
spring-boot开发
application.properties 文件配置
spring.datasource.url=jdbc:mysql://localhost:3306/hua?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=hua
spring.datasource.password=hua
#通过jpa完成数据库的相关操作
spring.jpa.database=MYSQL
server.port=5888
model
package com.example.demo.model;
import lombok.Data;
import javax.persistence.*;
import java.io.Serializable;
@Data
@Entity
@Table(name = "user")
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "name")
private int name;
@Column(name = "age")
private int age;
@Column(name = "sex")
private int sex;
@Column(name = "birthday")
private int birthday;
}
@Data
注解为 Lombok
提供,这里的作用是减少getter/setter/toString
方法
dao
package com.example.demo.dao;
import com.example.demo.model.User;
import org.springframework.data.repository.CrudRepository;
public interface UserRepository extends CrudRepository<User,Integer> {
User findByName(int name);
}
相关CRUD操作由 CrudRepository
接口的实现类完成
server
package com.example.demo.server;
import com.example.demo.dao.UserRepository;
import com.example.demo.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServer {
@Autowired
private UserRepository userRepository;
public Iterable<User> findAllUser(){
return userRepository.findAll();
}
public User findUserByName(int userName){
return userRepository.findByName(userName);
}
}
controller
package com.example.demo.controller;
import com.example.demo.model.User;
import com.example.demo.result.Result;
import com.example.demo.result.ResultGenerator;
import com.example.demo.server.UserServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping(value = "/user")
public class UserController {
@Autowired
private UserServer userServer;
@RequestMapping(value = "/all", method = RequestMethod.GET)
public @ResponseBody
Result getAllUsers() {
return ResultGenerator.getSuccessResult(userServer.findAllUser());
}
}
部署
直接打包部署 sprint-boot 项目,就可以实现通过 api 获取数据。
记得在控制台上部署相关端口,本例需要在防火墙上开起 5888 端口