SpringBoot和Vue实现数据对接--SpringBoot端
1、新建一个SpringBoot项目
勾选上这四个:
等待创建完成即可;
2、编写.yml文件
这里需要注意的是,端口需要与vue的端口区分开,不然会存在端口冲突的问题!
3、编写SpringBoot代码
Student.java
package com.example.myspring001.entity;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import lombok.Data;
@Data
@Entity
public class Student {
@Id
private int id;
private String name;
private int age;
private String jia;
}
StudentRepository.java
package com.example.myspring001.repository;
import com.example.myspring001.entity.Student;
import org.springframework.data.jpa.repository.JpaRepository;
public interface StudentRepository extends JpaRepository<Student,Integer> {
}
然后创建测试类Test:
接口处右键-->go to-->Test-->Create new Test:
ok即可:
测试类代码:
package com.example.myspring001.repository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
class StudentRepositoryTest {
@Autowired
private StudentRepository studentRepository;
@Test
void findAll(){
//尝试输出结果
System.out.println(studentRepository.findAll());
}
}
结果查了出来:
StudentController.java
package com.example.myspring001.controller;
import com.example.myspring001.entity.Student;
import com.example.myspring001.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/student")
public class StudentController {
@Autowired
private StudentRepository studentRepository;
@GetMapping("/findAll")
public List<Student> findAll(){
return studentRepository.findAll();
}
}
启动(未对接Vue版)!