这一天主要学习在数据库中增加数据时,Vue界面也增加数据
主要代码昨天已经写完了,今天来写后端内容
数据库中增加数据时,前端也增加数据,本质上就是查询数据库
而java中要查询到数据库,然后把数据返回给前端,主要有以下流程:
1.定义构造方法User,构造方法字段与数据库字段一致,该方法放在entity包中:
package com.example.springboot.entity;
import lombok.Data;
@Data//替换get/set方法
public class User {
private String name;
private Integer age;
private String sex;
private String phone;
private String status;
private String ward;
}
2.创建映射接口UserMapper,该接口放入mapper包下:
这个接口主要实现了查询数据库,并将结果封装成User,并装在List列表里,方便后续读取
这个接口对外暴露,期望能够被实现
package com.example.springboot.mapper;
import com.example.springboot.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface UserMapper {
@Select("select * from patient_information")
List<User> listUsers();
}
3.创建接口IUserService,该接口放入service包下:
该接口定义一个泛型为User的List列表,并对外暴露,等待方法实现
package com.example.springboot.service;
import com.example.springboot.entity.User;
import java.util.List;
public interface IUserService {
List<User> listUsers();
}
4.创建一个方法UserService,该方法放入service包的impl包下:
该方法实现了IUserSerivce接口,并实现了一个UserMapper方法的对象
这个方法的目的是将UserMapper拿到的数据库数据作为返回值返回
package com.example.springboot.service.impl;
import com.example.springboot.entity.User;
import com.example.springboot.mapper.UserMapper;
import com.example.springboot.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService implements IUserService {
@Autowired
UserMapper userMapper;
@Override
public List<User> listUsers() {
return userMapper.listUsers();
}
}
最后,创建一个类UserController,放在controller包下:
该类作为一个页面的入口。
该类使用自动装配将Mapper拿到的数据装配到IUserService中,并定义了一个方法用来返回UserService传过来的数据
package com.example.springboot.controller;
import com.example.springboot.entity.User;
import com.example.springboot.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
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;
@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
IUserService userService;
@GetMapping("/list")
public List<User> listUser(){
return userService.listUsers();
}
}
总的来说:user => usermapper&iuserservice => userservice(um)=>usercontroller(um,iuser)
um:usermapper
iuser:iuserservice