登录
首页 >  数据库 >  MySQL

后端Spring Boot+前端Android交互+MySQL增删查改(Java+Kotlin实现)

来源:SegmentFault

时间:2023-01-09 20:40:01 244浏览 收藏

本篇文章向大家介绍《后端Spring Boot+前端Android交互+MySQL增删查改(Java+Kotlin实现)》,主要包括MySQL、android、kotlin,具有一定的参考价值,需要的朋友可以参考一下。

1 前言&概述

这篇文章是基于这篇文章的更新,主要是更新了一些技术栈以及开发工具的版本,还有修复了一些Bug。

本文是

@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    private String name;
    private String password;
}

基本的

@Repository
public interface UserRepository extends CrudRepository {
    boolean existsByName(String name);
    User findByNameAndPassword(String name,String password);
}

一个需要注意的点是

@Transactional
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class UserService {
    private final UserRepository repository;

    public boolean exists(User user){
        return repository.existsByName(user.getName());
    }

    public User findByNameAndPassword(User user){
        return repository.findByNameAndPassword(user.getName(),user.getPassword());
    }

    public boolean insert(User user){
        repository.save(user);
        return true;
    }

    public boolean update(User user){
        if(repository.findById(user.getId()).isEmpty()){
            return false;
        }
        repository.save(user);
        return true;
    }

    public boolean deleteById(int id){
        if(!repository.existsById(id)){
            return false;
        }
        repository.deleteById(id);
        return true;
    }
}

注解解释如下:

  • @RestController
    @RequestMapping("/")
    @RequiredArgsConstructor(onConstructor = @__(@Autowired))
    public class UserController {
        private final UserService service;
    
        @PostMapping("sign/in/up")
        public ResponseBody signInUp(@RequestBody User user) {
            if (service.exists(user)) {
                User u = service.findByNameAndPassword(user);
                return new ResponseBody(u != null ? ResponseCode.SIGN_IN_SUCCESS : ResponseCode.SIGN_IN_FAILED, u != null ? u.getId() : "");
            }
            return new ResponseBody(service.insert(user) ? ResponseCode.SIGN_UP_SUCCESS : ResponseCode.SIGN_UP_FAILED, "");
        }
    
        @PutMapping("update")
        public ResponseBody update(@RequestBody User user) {
            return new ResponseBody(service.update(user) ? ResponseCode.UPDATE_SUCCESS : ResponseCode.UPDATE_FAILED, "");
        }
    
        @DeleteMapping("delete")
        public ResponseBody deleteByName(@RequestParam int id) {
            return new ResponseBody(service.deleteById(id) ? ResponseCode.DELETE_SUCCESS : ResponseCode.DELETE_FAILED, "");
        }
    
        @GetMapping("test")
        public String test() {
            return "test";
        }
    }

    注解解释如下: