Spring Boot 我想按日期限制用户输入

mrphzbgm  于 2022-12-23  发布在  Spring
关注(0)|答案(1)|浏览(256)

我尝试通过日期限制用户的输入,例如,如果第一次输入的日期为:2022 - 12 - 20,它只接受一周内的日期,所以最后可能的日期将是:2022 - 12 - 27,7天后。我想我必须使用查询来做这件事,因为我明白Hibernate没有这样的功能。
因此,我希望按日期限制数据输入,例如:第一个条目是2022 - 12 - 20我只能使用2022 - 12 - 21/22/23/.../27
这是我想要限制的实体:

@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "planDay")
@JsonIgnoreProperties(value = {"planDaysId"})
public class PlanDay {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long planDaysId;

    @Column
    private Date planDate;

    @Column
    private String weekday;

    @ManyToOne
    @JoinColumn(name = "planId", nullable = false)
    private Plans plans;

    @ManyToOne
    @JoinColumn(name = "medsId", nullable = false)
    private Meds meds;

    @Column
    private int medsToTake;
}

where planDate would be the attribute to limit. To save it I just do a planDayRepo.save(). Any Ideas?
也是我的控制器和服务:控制器:

@PostMapping(value = "/plan/save")
    public String savePlans(@RequestBody List<PlanDay> plans) {

        return saveService.savePlans(plans);
    }

服务(for只是为了让我可以更新pilNumber忽略它,我知道我不应该这样做):

public String savePlans(List<PlanDay> plans) {
        for (int i = 0; i < plans.size(); i++) {

            PlanDay planDay = plans.get(i);
            long medsId = planDay.getMeds().getMedsId();
            int medsToTake = planDay.getMedsToTake();
            int pillNumber = medsRepo.getReferenceById(medsId).getPillNumber();
            int pillUpdate = pillNumber - medsToTake;
            Meds updatePlanDay = medsRepo.findById(medsId).get();
            if (pillUpdate > 0) {
                updatePlanDay.setPillNumber(pillUpdate);
            } else {
                return "Error: No piils available";
            }
            planDayRepo.save(planDay);
        }

此致

pbpqsu0x

pbpqsu0x1#

您可以使用@PastOrPresent和@FutureOrPresent约束条件来确保planDate分别是过去或现在,或者是将来或现在。您还可以使用@Min和@Max约束条件来指定planDate字段允许的最小值和最大值。
下面是一个如何修改PlanDay实体类以添加验证约束的示例:

import javax.validation.constraints.*;

@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "planDay")
@JsonIgnoreProperties(value = {"planDaysId"})
public class PlanDay {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long planDaysId;

@Column
@PastOrPresent
@FutureOrPresent(groups = OneWeekInTheFuture.class)
@Min(value = 2022-12-20, groups = OneWeekInTheFuture.class)
@Max(value = 2022-12-27, groups = OneWeekInTheFuture.class)
private Date planDate;

    @Column
    private String weekday;

    @ManyToOne
    @JoinColumn(name = "planId", nullable = false)
    private Plans plans;

    @ManyToOne
    @JoinColumn(name = "medsId", nullable = false)
    private Meds meds;

    @Column
    private int medsToTake;

}

相关问题