写下自己的第一个API

最终成果:https://159.75.105.236:5888/user/all

相关工具及准备

1.自己去买一个服务器,腾讯云、阿里云都可以,直接安装宝塔(额外安装:java项目一键部署)

2.IntelliJ + spring-boot

spring-boot项目快速搭建

至少添加这部分依赖

实现第一个API

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方法

spring-boot相关注解使用

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 端口

结果

实现第一个API

相关文章:

  • 2021-10-26
  • 2021-06-10
  • 2021-07-30
  • 2022-12-23
  • 2022-12-23
  • 2021-05-02
  • 2021-11-20
猜你喜欢
  • 2021-09-06
  • 2022-02-20
  • 2021-04-02
  • 2022-12-23
  • 2022-12-23
  • 2021-10-19
相关资源
相似解决方案