iT邦幫忙

2023 iThome 鐵人賽

DAY 20
0
Mobile Development

Android與Spring Boot開發學習之旅系列 第 20

開發學習之旅 Day20 - 記帳應用API:支出資料請求

  • 分享至 

  • xImage
  •  

建立Entity類

定義實體類,該類包含支出的相關資訊,用於映射到expenses資料庫表。

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "_expenses")
public class ExpensesEntity {
    @CreatedBy
    @JsonIgnore
    @ManyToOne(fetch = FetchType.LAZY)
    private AppUserEntity appUser;
    @Id
    @GeneratedValue
    private Long id;
    private String expensesType;
    private String expensesName;
    private Integer expensesValue;
    @LastModifiedDate
    @JsonIgnore
    private LocalDate recorded_at;
}

建立Repository類

Expenses Repository 接口,通過自定義的JPQL查詢對ExpensesEntity進行資料庫操作。

@Repository
public interface ExpensesRepository extends JpaRepository<ExpensesEntity, Long> {

    //用於查找在給定日期下,屬於特定使用者的支出記錄
    @Query("SELECT e FROM ExpensesEntity e WHERE DATE(e.recorded_at) = :date AND e.appUser = :appUser")
    List<ExpensesEntity> findExpensesByDateAndAppUser(@Param("date") LocalDate date, AppUserEntity appUser);

    //查找屬於特定使用者的所有支出記錄
    @Query("SELECT e FROM ExpensesEntity e WHERE e.appUser = :appUser")
    List<ExpensesEntity> findAllExpensesByAppUser(AppUserEntity appUser);

    //用於刪除資料庫中的支出記錄,並且只會刪除指定 id 和 特定使用者 的記錄。
    @Transactional
    @Modifying
    @Query("DELETE FROM ExpensesEntity d WHERE d.id = :id AND d.appUser = :appUser")
    void deleteByIdAndAppUser(@Param("id") Long id, @Param("appUser") AppUserEntity appUser);

}

建立Service類

用於處理支出相關邏輯,返回相應的響應數據。

@Service
@AllArgsConstructor
public class ExpensesService {
    private final ExpensesRepository expensesRepository;

    public Map<String, Object> getExpenses(String request) {
        var response = new LinkedHashMap<String, Object>();
        var appUser = (AppUserEntity) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        var Data = new ArrayList<>();
        LocalDate date = LocalDate.parse(request, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        var expensesData = expensesRepository.findExpensesByDateAndAppUser(date,appUser);
        if (!expensesData.isEmpty()){
            for(var expenses:expensesData){
                Data.add(expenses);
            }
        }
        response.put("status", "成功");
        response.put("message","ok");
        response.put("expensesDataList", Data);
        return  response;
    }
    public Map<String, Object> getAllExpenses() {
        var response = new LinkedHashMap<String, Object>();
        var appUser = (AppUserEntity) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        var Data = new ArrayList<>();
        var expensesData = expensesRepository.findAllExpensesByAppUser(appUser);
        if (!expensesData.isEmpty()){
            for(var expenses:expensesData){
                Data.add(expenses);
            }
        }
        response.put("status", "成功");
        response.put("message","ok");
        response.put("expensesDataList", Data);
        return  response;
    }
    public Map<String, Object> addExpenses(ExpensesRequest request){
        var response = new LinkedHashMap<String, Object>();
        var appUser = (AppUserEntity) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        var expensesData = ExpensesEntity
                .builder()
                .appUser(appUser)
                .expensesType(request.getExpensesType())
                .expensesName(request.getExpensesName())
                .expensesValue(request.getExpensesValue())
                .recorded_at(request.getRecorded_at())
                .build();
        expensesRepository.save(expensesData);
        response.put("status", "成功");
        response.put("message", "ok");
        return response;
    }

    public Map<String, Object> deleteExpenses(Long request){
        var response = new LinkedHashMap<String, Object>();
        expensesRepository.deleteById(request);
        response.put("status", "成功");
        response.put("message", "ok");
        return response;
    }
}

建立Controller類

Spring Boot控制器,用於處理支出相關的 HTTP 請求。

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/user")
@Tag(name = "支出模塊")
public class ExpensesController {

    private final ExpensesService service;

    @GetMapping("/expenses")
    @Operation(summary = "支出列表資料")
    public ResponseEntity<?> getExpenses(
            @RequestParam("date") String date
    ) {
        return ResponseEntity.ok(service.getExpenses(date));
    }

    @GetMapping("/expenses/all")
    @Operation(summary = "支出列表資料")
    public ResponseEntity<?> getAllExpenses() {
        return ResponseEntity.ok(service.getAllExpenses());
    }



    @PostMapping("/expenses")
    @Operation(summary = "新增支出資料")
    public ResponseEntity<?> addExpenses(
            @RequestBody ExpensesRequest request
    ) {
        return ResponseEntity.ok(service.addExpenses(request));
    }

    @DeleteMapping("/expenses")
    @Operation(summary = "刪除支出記錄")
    public ResponseEntity<?> deleteExpenses(
            @RequestParam("id") Long request
    ) {
        return ResponseEntity.ok(service.deleteExpenses(request));
    }
}

建立Request類

定義用於註冊的請求資料結構。

@Data
@Schema(name = "ExpensesRequest", description = "支出新增請求")
public class ExpensesRequest {
    @Schema(description = "支出名稱")
    private String expensesName;
    @Schema(description = "支出金額")
    private Integer expensesValue;
    @Schema(description = "支出類型")
    private String expensesType;
    @Schema(description = "使用者記錄時間")
    private LocalDate recorded_at;
}

上一篇
開發學習之旅 Day19 - 全局異常處理
下一篇
開發學習之旅 Day21 - 記帳應用:Android端請求支出資料
系列文
Android與Spring Boot開發學習之旅30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言