如何使用Spring Data JPA查找最近7天的数据?

时间:2019-05-29 10:54:06

标签: spring-boot spring-data-jpa

我想找到订单表中的最后7个订单,我该怎么做?

这是订单表

CREATE TABLE `orders` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `total` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL,
  `service_charge` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL,
  `vat` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL,
  `delivery_charge` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL,
  `subtotal` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL,
  `point_used` int(5) DEFAULT NULL,
  `discount_id` bigint(20) DEFAULT NULL,
  `user_id` bigint(20) NOT NULL,
  `address_id` bigint(20) NOT NULL,
  `payement_type` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL,
  `payment_status` varchar(10) COLLATE utf8mb4_unicode_ci NOT NULL,
  `message` mediumtext COLLATE utf8mb4_unicode_ci,
  `transaction_id` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
  `invoice` enum('yes','no') COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'no',
  `status` enum('pending','accepted','processed','on-way','delivered','cancelled') COLLATE utf8mb4_unicode_ci NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `address_id` (`address_id`),
  KEY `user_id` (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

这是我正在使用的服务

public List<Order> getLastSevenDaysOrders(User user, String todayString, String sevenDaysBeforeString) {
        ArrayList<Order> orders = new ArrayList<>();
        orderRepository.findByUserAndCreatedAtBetween(user, todayString, sevenDaysBeforeString).forEach(orders::add);
        return orders;
    }

这是我的存储库。

List<Order> findByUserAndCreatedAtBetween(User user, String todayString, String sevenDaysBeforeString);

这是我的控制人

@RequestMapping(value = "/order/recent", method = RequestMethod.POST)
    public JsonNode getRecentOrder(HttpServletRequest httpServletRequest, @RequestBody String userId) throws IOException {

        long startTime = System.currentTimeMillis();
        utility.printCallingUrl(httpServletRequest);

        JSONObject request = new JSONObject(userId);

        JSONArray response = new JSONArray();

        //Order order = new Order();
        List<Order> orders = new ArrayList<>();

        String auth = httpServletRequest.getHeader("Authorization");
        String authentication = utility.getBasicAuth();

        if (auth.equals(authentication)) {
            try {



                Calendar calendar = Calendar.getInstance();
                String pattern = "yyyy-MM-dd HH:mm:ss";
                DateFormat dateFormat = new SimpleDateFormat(pattern);
                Date today = calendar.getTime();
                String todayString = dateFormat.format(today);

                calendar.add(Calendar.DAY_OF_MONTH, -7);
                Date sevenDaysBefore = calendar.getTime();
                String sevenDaysBeforeString = dateFormat.format(sevenDaysBefore);

                User user = userService.getUser(request.getLong("user_id"));

                orders = orderService.getLastSevenDaysOrders(user, todayString, sevenDaysBeforeString);

                if (orders.size() > 0) {
                    for (Order order : orders) {
                        JSONObject response2 = new JSONObject();
                        response2.put("receiversName", order.getAddress().getReceiversName());
                        response2.put("address", order.getAddress().getAddress());
                        response2.put("nearbyLandmark", order.getAddress().getNearbyLandmark());
                        response2.put("receiversContact", order.getAddress().getReceiversContact());
                        response2.put("district", order.getAddress().getDistrict().getNameBn());
                        response2.put("division", order.getAddress().getDivision().getNameBn());
                        response2.put("village", order.getAddress().getVillage());
                        response2.put("name", order.getUser().getName());
                        response2.put("userId", order.getUser().getId());
                        response2.put("upazilla", order.getAddress().getUpazilla().getNameBn());
                        response2.put("vat", order.getVat());
                        response2.put("deliveryCharge", order.getDeliveryCharge());
                        response2.put("discountAmount", order.getDiscount().getAmount());
                        response2.put("discountCode", order.getDiscount().getCode());
                        response2.put("discountName", order.getDiscount().getName());
                        response2.put("discountId", order.getDiscount().getId());
                        response2.put("pointUsed", order.getPointUsed());
                        response2.put("message", order.getMessage());
                        response2.put("transactionId", order.getTransactionId());
                        response2.put("createdAt", order.getCreatedAt());
                        response2.put("total", order.getTotal());
                        response2.put("serviceCharge", order.getServiceCharge());
                        response2.put("subtotal", order.getSubtotal());
                        response2.put("orderId", order.getId());
                        response2.put("invoice", order.getInvoice());
                        response2.put("contact", order.getUser().getContact());
                        response2.put("payementType", order.getPayementType());
                        response2.put("paymentStatus", order.getPaymentStatus());
                        response2.put("status", order.getStatus());

                        response.put(response2);
                    }

                    Log log = utility.saveLog(KeyWord.GET_ORDERS, KeyWord.CMS, httpServletRequest, "200", request, new JSONObject().put("data", response), startTime);

                    if (log != null) {
                        utility.showMessage("Log inserted successfully with ID " + log.getId());
                    } else {
                        utility.showMessage("Log not inserted");
                    }
                } else {
                    response = new JSONArray();
                    Log log = utility.saveLog(KeyWord.GET_ORDERS, KeyWord.CMS, httpServletRequest, "500", request, new JSONObject().put("data", response), startTime);

                    if (log != null) {
                        utility.showMessage("Log inserted successfully with ID " + log.getId());
                    } else {
                        utility.showMessage("Log not inserted");
                    }
                }

            } catch (Exception e) {
                utility.showMessage(e.toString());
                return mapper.readTree(utility.createResponse(500, KeyWord.ERROR, e.toString()).toString());
            }

        } else {
            return mapper.readTree(utility.createResponse(500, KeyWord.ERROR, KeyWord.AUTHENTICATION).toString());
        }

        return mapper.readTree(response.toString());
    }

订单模型

@Entity
@Table(name = "orders")
public class Order {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    @Expose
    private long id;
    @Column(name = "total")
    @Expose
    private String total;
    @Column(name = "service_charge")
    @Expose
    private String serviceCharge;
    @Column(name = "vat")
    @Expose
    private String vat;
    @Column(name = "delivery_charge")
    @Expose
    private String deliveryCharge;
    @Column(name = "subtotal")
    @Expose
    private String subtotal;
    @Column(name = "point_used")
    @Expose
    private int pointUsed;

    // @Column(name = "discount_id")
    // private long discountId;

    @ManyToOne
    @JoinColumn(name = "discount_id")
    @Expose
    Discount discount;
    @ManyToOne
    @Expose
    User user;
    @OneToOne
    @Expose
    Address address;

    @Column(name = "payement_type")
    @Expose
    private String payementType;
    @Column(name = "payment_status")
    @Expose
    private String paymentStatus;
    @Column(name = "message")
    @Expose
    private String message;
    @Column(name = "transaction_id")
    @Expose
    private String transactionId;
    @Column(name = "invoice")
    @Expose
    private String invoice;
    @Column(name = "status")
    @Expose
    private String status;
    @Column(name = "created_at")
    @Expose
    private String createdAt;
    @Column(name = "updated_at")
    @Expose
    private String updatedAt;

    public Order() {
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getTotal() {
        return total;
    }

    public void setTotal(String total) {
        this.total = total;
    }

    public String getVat() {
        return vat;
    }

    public void setVat(String vat) {
        this.vat = vat;
    }

    public String getServiceCharge() {
        return serviceCharge;
    }

    public void setServiceCharge(String serviceCharge) {
        this.serviceCharge = serviceCharge;
    }

    public String getDeliveryCharge() {
        return deliveryCharge;
    }

    public void setDeliveryCharge(String deliveryCharge) {
        this.deliveryCharge = deliveryCharge;
    }

    public String getSubtotal() {
        return subtotal;
    }

    public void setSubtotal(String subtotal) {
        this.subtotal = subtotal;
    }

    public int getPointUsed() {
        return pointUsed;
    }

    public void setPointUsed(int pointUsed) {
        this.pointUsed = pointUsed;
    }

    public Discount getDiscount() {
        return discount;
    }

    public void setDiscount(Discount discount) {
        this.discount = discount;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public String getPayementType() {
        return payementType;
    }

    public void setPayementType(String payementType) {
        this.payementType = payementType;
    }

    public String getPaymentStatus() {
        return paymentStatus;
    }

    public void setPaymentStatus(String paymentStatus) {
        this.paymentStatus = paymentStatus;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getTransactionId() {
        return transactionId;
    }

    public void setTransactionId(String transactionId) {
        this.transactionId = transactionId;
    }

    public String getInvoice() {
        return invoice;
    }

    public void setInvoice(String invoice) {
        this.invoice = invoice;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(String createdAt) {
        this.createdAt = createdAt;
    }

    public String getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(String updatedAt) {
        this.updatedAt = updatedAt;
    }

}

订单存储库

@Repository
public interface OrderRepository extends PagingAndSortingRepository<Order, Long> {

    List<Order> findByUserAndCreatedAtBetween(User user, String todayString, String sevenDaysBeforeString);

}

在编写存储库方法时,服务中我在做错什么? 我得到一个空白数组。我认为编写findByUserAndCreatedAtBetween时出现了问题。如果能得到任何建议,那就太好了。

1 个答案:

答案 0 :(得分:0)

您的合同

List<Order> findByUserAndCreatedAtBetween(User user, String todayString, String sevenDaysBeforeString);

将日期参数作为字符串获取。这是不对的。 Spring JPA可与Date配合使用。

// Repository 
List<Order> findByUserAndCreatedAtBetween(User user, Date today, String Date sevenDaysBefore);

// Service
public List<Order> getLastSevenDaysOrders(User user, Date today, Date sevenDaysBefore) {       
        return orderRepository.findByUserAndCreatedAtBetween(user, today, sevenDaysBefore);
    }

然后

Calendar calendar = Calendar.getInstance();
Date today = calendar.getTime();

calendar.add(Calendar.DAY_OF_MONTH, -7);
Date sevenDaysBefore = calendar.getTime();

User user = userService.getUser(request.getLong("user_id"));

orders = orderService.getLastSevenDaysOrders(user, today, sevenDaysBefore);