SpringBoot + ajax 实现分页和增删查改
在Spring Boot中实现分页和增删查改,你可以使用spring-data-jpa
进行数据库操作,结合ajax
实现前后端的异步交互。以下是一个简单的示例:
实体类(User.java)
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
// 省略getter和setter
}
仓库接口(UserRepository.java)
public interface UserRepository extends JpaRepository<User, Long> {
Page<User> findAll(Pageable pageable);
}
服务类(UserService.java)
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public Page<User> getUsers(int page, int size) {
Pageable pageable = PageRequest.of(page, size);
return userRepository.findAll(pageable);
}
// 增删查改方法
public User saveUser(User user) {
return userRepository.save(user);
}
public User getUserById(Long id) {
return userRepository.findById(id).orElse(null);
}
public void deleteUserById(Long id) {
userRepository.deleteById(id);
}
}
控制器(UserController.java)
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/page")
public ResponseEntity<?> getUsers(@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size) {
Page<User> users = userService.getUsers(page, size);
return ResponseEntity.ok(users);
}
@PostMapping("/")
public ResponseEntity<?> saveUser(@RequestBody User user) {
User savedUser = userService.saveUser(user);
return ResponseEntity.ok(savedUser);
}
@GetMapping("/{id}")
public ResponseEntity<?> getUserById(@PathVariable Long id) {
User user = userService.getUserById(id);
return ResponseEntity.ok(user);
}
@DeleteMapping("/{id}")
public ResponseEntity<?> deleteUserById(@PathVariable Long id) {
userService.deleteUserById(id);
return ResponseEntity.ok("User deleted successfully");
}
}
前端(ajax请求示例)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
评论已关闭