Postman使用实例
实体类Emp
java
package com.example.springboot_postman.pojo;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.io.Serializable;
/**
* @Author moon
* @Date 2023/10/2 18:29
* @Description
*/
@Entity
@Table(name = "t_emp")
@Data
@AllArgsConstructor
@NoArgsConstructor
@JsonIgnoreProperties(value = { "hibernateLazyInitializer"})
public class Emp implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "emp_id")
private int id;
@Column(name = "emp_name")
private String name;
@Column(name = "age")
private int age;
@Column(name = "gender")
private String gender;
@Column(name = "email")
private String email;
}
JPA接口EmpDao
java
package com.example.springboot_postman.dao;
import com.example.springboot_postman.pojo.Emp;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* @Author moon
* @Date 2023/10/2 18:43
* @Description
*/
public interface EmpDao extends JpaRepository<Emp, Integer> {
}
1. 分页查询
EmpService:
java
public Page<Emp> queryByPage(Integer page, Integer size) {
Pageable pageable = PageRequest.of(page, size,Sort.by(Sort.Direction.DESC, "id"));
return empDao.findAll(pageable);
}
EmpController
java
@RequestMapping("/getByPage")
public ResponseEntity<Page<Emp>> queryByPage(@RequestBody Map<String, Integer> map) {
System.out.println(map.get("page") + map.get("size"));
return ResponseEntity.ok(this.EmpService.queryByPage(map.get("page"), map.get("size")));
}
2. 根据id查询
EmpService:
java
public Emp queryById(Integer id) {
Emp emp = new Emp();
emp.setId(id);
return empDao.getOne(emp.getId());
}
EmpController
java
@PostMapping
public ResponseEntity<Emp> add(Emp Emp) {
return ResponseEntity.ok(this.EmpService.insert(Emp));
}
3. 增
EmpService
java
public Emp insert(Emp emp) {
empDao.save(emp);
return emp;
}
EmpController
java
@PostMapping
public ResponseEntity<Emp> add(@RequestBody Emp Emp) {
System.out.println(Emp);
return ResponseEntity.ok(this.EmpService.insert(Emp));
}
4. 删
EmpService
java
public Boolean deleteById(Integer id) {
Emp emp = new Emp();
emp.setId(id);
empDao.deleteById(emp.getId());
return true;
}
EmpController
java
@DeleteMapping("{id}")
public ResponseEntity<Boolean> deleteById(@PathVariable Integer id) {
return ResponseEntity.ok(this.EmpService.deleteById(id));
}
5. 改
EmpService
java
public Emp update(Emp emp) {
empDao.save(emp);
return emp;
}
EmpController
java
@PutMapping
public ResponseEntity<Emp> edit(@RequestBody Emp Emp) {
return ResponseEntity.ok(this.EmpService.update(Emp));
}
其中分页管理也可以这样写
java
@GetMapping
public ResponseEntity<Page<Emp>> queryByPage(@RequestBody Map<String, Integer> map) {
return ResponseEntity.ok(this.EmpService.queryByPage(map.get("page"), map.get("size")));
}