user表
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` bigint NOT NULL AUTO_INCREMENT,
`name` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '名字',
`age` int DEFAULT NULL COMMENT '年龄',
`sex` varchar(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '性别',
`address` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '地址',
`phone` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '手机',
`creat_time` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '创建时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
springboot起步依赖
Result
package com.example.common;
public class Result<T> {
private String code;
private String msg;
private T data;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public Result() {
}
public Result(T data) {
this.data = data;
}
public static Result success() {
Result result = new Result<>();
result.setCode("0");
result.setMsg("成功");
return result;
}
public static <T> Result<T> success(T data) {
Result<T> result = new Result<>(data);
result.setCode("0");
result.setMsg("成功");
return result;
}
public static Result error(String code, String msg) {
Result result = new Result();
result.setCode(code);
result.setMsg(msg);
return result;
}
}
WebMvcConfig
package com.example.common;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedHeaders("Content-Type","X-Requested-With","accept,Origin","Access-Control-Request-Method","Access-Control-Request-Headers","token")
.allowedMethods("*")
.allowedOrigins("*")
.allowCredentials(true);
}
}
UserController
package com.example.controller;
import com.example.common.Result;
import com.example.entity.User;
import com.example.service.UserService;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
@RestController
@RequestMapping("/user")
public class UserController {
@Resource
private UserService userService;
// 新增用户
@PostMapping
public Result add(@RequestBody User user) {
userService.save(user);
return Result.success();
}
// 修改用户
@PutMapping
public Result update(@RequestBody User user) {
userService.save(user);
return Result.success();
}
// 删除用户
@DeleteMapping("/{id}")
public void delete(@PathVariable("id") Long id) {
userService.delete(id);
}
// 根据id查询用户
@GetMapping("/{id}")
public Result<User> findById(@PathVariable Long id) {
return Result.success(userService.findById(id));
}
// 查询所有用户
@GetMapping
public Result<List<User>> findAll() {
return Result.success(userService.findAll());
}
// 分页查询用户
@GetMapping("/page")
public Result<Page<User>> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
@RequestParam(defaultValue = "10") Integer pageSize,
@RequestParam(required = false) String name) {
return Result.success(userService.findPage(pageNum, pageSize, name));
}
}
UserRepository
package com.example.dao;
import com.example.entity.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
@Query(value = "select * from user where name like %?1%", nativeQuery = true)
Page<User> findByNameLike(String name, Pageable pageRequest);
}
User
package com.example.entity;
import javax.persistence.*;
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private Integer age;
private String sex;
private String address;
private String phone;
@Column(name = "create_time")
private String createTime;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
}
UserService
package com.example.service;
import com.example.dao.UserRepository;
import com.example.entity.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@Service
public class UserService {
@Resource
private UserRepository userRepository;
public void save(User user) {
String now = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
user.setCreateTime(now);
userRepository.save(user);
}
public void delete(Long id) {
userRepository.deleteById(id);
}
public User findById(Long id) {
return userRepository.findById(id).orElse(null);
}
public List<User> findAll() {
return userRepository.findAll();
}
public Page<User> findPage(Integer pageNum, Integer pageSize, String name) {
// 构建分页查询条件
Sort sort = new Sort(Sort.Direction.DESC, "create_time");
Pageable pageRequest = PageRequest.of(pageNum - 1, pageSize, sort);
return userRepository.findByNameLike(name, pageRequest);
}
}