How auto update value into database in spring boot and JPA

In spring boot we have @Scheduled(fixedDelay = 2000) where we can define the refresh time of the server as fixedDelay. It will refresh the server and execute the business method into the mentioned time stamp.

Well, In this article, I am going to show you how can you update the status in the database at a specific time. The below example is about the car booking system. where students can book parking slots for the time period and the booked slot should be automatic turn into available once the booking time is over.

Booking.JSP

Design a front-end form that allows customers to feed the value and book a slot for a time period.

In the below code, We have defined a specific date and time format by using

<%DateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd"); %>

And 

<sf:input type="date" class="form-control form-control-lg" id="fromBookingDate" path="fromBookingDate" placeholder="dd/MM/yyyy" min="<%= df.format(new java.util.Date())%>"/>

<%@page import="java.text.DateFormat"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="sf"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="http://java.sun.com/jstl/core_rt" prefix="crt"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="s"%>
<%DateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd"); %>
<style><%@include file="/WEB-INF/css/bookingview.css"%></style>
<section class="vh-100 gradient-custom content">
  <div class="container py-5 h-100">
    <div class="row justify-content-center align-items-center h-100">
      <div class="col-12 col-lg-9 col-xl-7">
        <div class="card shadow-2-strong card-registration" style="border-radius: 15px;">
          <div class="card-body p-4 p-md-5">
           <%@include file="businessMessage.jsp" %>
            <h3 class="mb-4 pb-2 pb-md-0 mb-md-5">Book Parking</h3>
            <sf:form method="post" action="${pageContext.request.contextPath}/addBooking" modelAttribute="form">
            <sf:input type="hidden" id="id" class="form-control form-control-lg" path="id" name="id" value="${form.id}"/>
              <div class="row">
              
                <div class="col-md-6 mb-4">
                  <div class="form-outline">   
                  <s:bind path="firstName">
                  <label class="form-label" for="firstName">First Name</label>
                  <sf:input type="text" id="firstName" class="form-control form-control-lg" path="firstName" name="firstName" value="${user.firstName}" readonly="true"/>
                  <font color="red" style="font-size: 15px"><sf:errors path="${status.expression}" /></font>
                  </s:bind>      
                  
                  
                  </div>
     
                </div>
                <div class="col-md-6 mb-4">
                
                  <div class="form-outline">
                  <s:bind path="lastName">
                  <label class="form-label" for="lastName">Last Name</label>
                    <sf:input type="text" id="lastName" class="form-control form-control-lg" path="lastName" value="${user.lastName}" readonly="true"/>
                    <font color="red" style="font-size: 15px"><sf:errors path="${status.expression}" /></font>
                  </s:bind>
                  </div>
               
                </div>
                
              </div>

              <div class="row">

                <div class="col-md-6 mb-4 pb-2">
                 <s:bind path="email">
                  <div class="form-outline">
                  <label class="form-label" for="email">Email</label>
                    <sf:input type="tel" id="email" class="form-control form-control-lg" path="email" value="${user.email}" readonly="true"/>
                      <font color="red" style="font-size: 15px"><sf:errors path="${status.expression}" /></font>
                  </div>
     </s:bind>
                </div> 
                
                <div class="col-md-6 mb-4 pb-2">
                 <s:bind path="phoneNumber">
                  <div class="form-outline">
                   <label class="form-label" for="phoneNumber">Phone Number</label>
                    <sf:input type="tel" id="phoneNumber" class="form-control form-control-lg" path="phoneNumber" value="${user.phoneNumber}" readonly="true"/>
                    <font color="red" style="font-size: 15px"><sf:errors path="${status.expression}" /></font>
                  </div>
     </s:bind>
                </div> 
                
              </div>
              
                <div class="row">

                <div class="col-md-6 mb-4 pb-2">
                 <s:bind path="parkingName">
                  <div class="form-outline">
                  <label class="form-label" for="parkingName">Parking Name</label>
                    <sf:input type="tel" id="parkingName" class="form-control form-control-lg" path="parkingName" value="${parkingDTO.parkingName}" readonly="true"/>
                    <font color="red" style="font-size: 15px"><sf:errors path="${status.expression}" /></font>
                  </div>
     </s:bind>
                </div> 
                
                   <div class="col-md-6 mb-4 pb-2">
                 <s:bind path="address">
                  <div class="form-outline">
                  <label class="form-label" for="address">Address</label>
                    <sf:input type="tel" id="address" class="form-control form-control-lg" path="address" value="${parkingDTO.address}" readonly="true"/>
                    <font color="red" style="font-size: 15px"><sf:errors path="${status.expression}" /></font>
                  </div>
     </s:bind>
                </div>
                
               <div class="col-md-6 mb-4 pb-2">    
               <label class="form-label select-label">Select Slot</label><br/>       
                 
                  <select class="select form-control-lg" name="slotId">
                  <option value="1" disabled>Select slot</option>
                    <c:forEach items="${slotList}" var="list" varStatus="u">
                    <option value="${list.id}">${list.slot}</option>
                    </c:forEach>
                  </select>
                  
                </div>
  
                
              </div>
              
                <div class="row">
                
                <div class="col-md-6 mb-4 d-flex align-items-center">
                  <s:bind path="fromBookingDate">
                  <div class="form-outline datepicker w-100">
                  <label for="fromBookingDate" class="form-label">FromBookingDate</label>
                    <sf:input type="date" class="form-control form-control-lg" id="fromBookingDate" path="fromBookingDate" placeholder="dd/MM/yyyy" min="<%= df.format(new java.util.Date())%>"/>
                     <font color="red" style="font-size: 15px"><sf:errors path="${status.expression}" /></font>
                  </div>
                  </s:bind>
                </div>
                
                
                 <div class="col-md-6 mb-4 d-flex align-items-center">
                  <s:bind path="fromTime">
                  <div class="form-outline datepicker w-100">
                  <label for="fromTime" class="form-label">FromTime</label>
                    <sf:input type="time" class="form-control form-control-lg" id="fromTime" path="fromTime" placeholder="HH:MM:SS"/>
                    <font color="red" style="font-size: 15px"><sf:errors path="${status.expression}" /></font>
                  </div>
                  </s:bind>
                </div>
                
                </div>
              
               <div class="row">
                
                <div class="col-md-6 mb-4 d-flex align-items-center">
                  <s:bind path="toBookingDate">
                  <div class="form-outline datepicker w-100">
                  <label for="toBookingDate" class="form-label">ToBookingDate</label>
                    <sf:input type="date" class="form-control form-control-lg" id="toBookingDate" path="toBookingDate" placeholder="dd/MM/yyyy" min="<%= df.format(new java.util.Date())%>"/>
                    <font color="red" style="font-size: 15px"><sf:errors path="${status.expression}" /></font>
                  </div>
                  </s:bind>
                </div>
                
                
                 <div class="col-md-6 mb-4 d-flex align-items-center">
                  <s:bind path="toTime">
                  <div class="form-outline datepicker w-100">
                  <label for="toTime" class="form-label">ToTime</label>
                  
                    
                    <sf:input type="time" class="form-control form-control-lg" id="toTime" path="toTime" placeholder="HH:MM:SS" min="00" max="24"/>
                    <font color="red" style="font-size: 15px"><sf:errors path="${status.expression}" /></font>
                    
                    
                  </div>
                  </s:bind>
                </div>
                
                </div>
 
                <c:choose>
  				<c:when test="${form.id>0}">
   				  <div class="mt-4 pt-2">
                <input class="btn btn-primary btn-lg" type="submit" value="Book Slot" />
              </div>   
 			</c:when>

  			<c:otherwise>
             <div class="mt-4 pt-2">
                <input class="btn btn-primary btn-lg" type="submit" value="Book Slot" />
              </div>
  			</c:otherwise>
   </c:choose> 
           </sf:form>
          
          </div>
        </div>
      </div>
    </div>
  </div>
</section>

From the above get the values and store them in the database, the same as we do in basic spring boot applications by using controllers and services.

Auto update value into the database in spring boot and JPA

Create a custom method under the service layer. and add the annotation @Scheduled(fixedDelay = 1000) at the top of the method.

Now, write the business logic as per the requirement, In the below code snippet, We are reading the booking details from the database, finding the current date and time, comparing both the dates and time, and updating the slot records.

This method will keep executing in every second and make the required changes into the database.

@Scheduled(fixedDelay = 1000)
 public void scheduleFixedDelayTask() {
     List<BookingDTO> bookingList = dao.findAll();	    
     List<SlotDTO> slotList = slotDAO.findAll();
     
     for (BookingDTO bookingDTO : bookingList) {
     	
     	long slot_id = bookingDTO.getSlotId();
     	String toBookingDate = DataUtility.getDateString1(bookingDTO.getToBookingDate());
     	
     	String toTime = bookingDTO.getToTime();
     	String finalBookingTime = toBookingDate+" "+toTime+":00";
     	System.out.println("To Booking Date and time: "+finalBookingTime);
     	System.out.println("Current Time: "+DataUtility.getCurrentTimestamp());
     	
     	int b3 = DataUtility.getCurrentTimestamp().compareTo(DataUtility.getDateAndTime(finalBookingTime));  
     	System.out.println("Compare Status: "+b3);
     	
     	SlotDTO slotDTO = slotDAO.findById(slot_id);
     	
     	if(slotDTO.isStatus()) {
     		//System.out.println("Current Time: "+DataUtility.getCurrentTimestamp());
     	}else if(b3>=0){ 		
     		slotDTO.setStatus(true);
     		slotDAO.saveAndFlush(slotDTO);
     	}
   
  }

Here are some, utility methods that will help to data conversion into the required fromat.

Class Utility{
    public static final String APP_DATE_FORMAT1 = "yyyy-MM-dd";
    private static final SimpleDateFormat formatter1 = new SimpleDateFormat(APP_DATE_FORMAT1);

public static String getDateString1(Date date) {
           
           
  try {
   if (date != null) {
    return formatter1.format(date);
   } else {
    return "";
   }
  } catch (Exception e) {
   return "";
  }

 }

}