Searching the Records on basis of Date - spring

Hi I need to find the records on the basis of Billed date, Now when the user hits the Url
"/bills/due/25-11-2020" the search would fetch me all records on date 25 Nov 2020
public interface BillsRepository extends JpaRepository<Bills, Long> {
#Query(value = "Select Bills.billedDate,Bills.billNo, Bills.billedTo from Bills where Bills.billedDate is like %?1%", nativeQuery = true)
public List<Bills> findByDate(#Param("date") Date date);
}
and my service Method
#Override
public List<Bills> getbillsByDate(Date date) throws ParseException {
List<Bills> billsbydate = billRepo.findByDate(new SimpleDateFormat("yyyy-mm-dd").parse(date.toString()));
return billsbydate;
}
Whenever I am hitting the Url from my Controller method
#GetMapping("bills/due/{date}")
public ResponseEntity<List<Bills>> getByDate(#PathVariable("date") Date date) throws ParseException {
List<Bills> billsByDate = billService.getbillsByDate(date);
return ResponseEntity.ok(billsByDate);
}
it throws an exception
2021-11-16 08:18:58.396 WARN 29141 --- [nio-9070-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.util.Date'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [#org.springframework.web.bind.annotation.PathVariable java.util.Date] for value '15-11-2021'; nested exception is java.lang.IllegalArgumentException]
Any am Newbie to Spring date JPA, So any help would be appreciated
Thnks

As a dirty solution, In your controller try this.
Instead of #PathVariable("date") Date date use #PathVariable("date") String date and then convert the String date to Date date - the same way you are doing in your service.
OR
Follow this:
https://www.baeldung.com/spring-date-parameters
This URL has your outlined the exact error you are facing.

Related

Failed parsing for a LocalDate value while using Spring Data Rest

I am still a newbie with Spring Data Rest and I'm having some issues with it while I have to parse a LocalDate value to an endpoint. I have searched info's in other topics too but I'm still stucked, this is the problem:
I have one Entity with this code .
#Entity
#Table(name="calendario_parcheggio")
#Setter
#Getter
public class CalendarioParcheggio {
#Id
#Column(name="data_parcheggio")
#DateTimeFormat(iso = DateTimeFormat.ISO.DATE )
#JsonFormat(pattern="yyyy-MM-dd")
private LocalDate data;
#Column(columnDefinition = "ENUM('ATTIVO', 'ARCHIVIATO')")
#Enumerated(EnumType.STRING)
private Stato stato;
#OneToMany(cascade=CascadeType.ALL)
#JoinColumn(name="data_parcheggio")
private List<Parcheggio> parcheggio;
public enum Stato {
ATTIVO,
ARCHIVIATO,
}
}
It's an Entity linking the Date and its status for a Parking that works hourly.Matching this table on MySQL
CREATE TABLE calendario_parcheggio (
data_parcheggio DATE PRIMARY KEY,
stato ENUM ('ATTIVO','ARCHIVIATO') NOT NULL DEFAULT ('ATTIVO')
);
When I start the server everything is ok , but when i try (by browser or Postman) to check the data of a particular instance (in my case : "http://localhost:8080/parkingsystem/api/calendario-parcheggio/2022-10-18") ,I get this problem :
{"cause":
{"cause":
{"cause": null,
"message": "Text '2022-10-18' could not be parsed at index 2"
},
"message": "Parse attempt failed for value [2022-10-18]"
},
"message": "Failed to convert from type [java.lang.String] to type [java.time.LocalDate] for value '2022-10-18';
nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2022-10-18]"
}
And this is the Repository
#RepositoryRestResource(collectionResourceRel="calendarioParcheggio", path="calendario-parcheggio")
public interface CalendarioParcheggioRepository extends JpaRepository<CalendarioParcheggio, LocalDate> {
}
Can you help me to find the solution please?I hope I have explained the problem well enough, my English is still in training :)

Spring data elastic search date issue when search

I am using spring-boot-starter-parent 2.5.4 and elasticsearch 7.12.1 and basically am able to insert a document with createDate as field successfully but unable to search.
I have a Spring rest webservice that contains search functionality that search by range of date and contains the request in json below:
{
"dateTo": "20210901T152702.620+04:00",
"dateFrom": "20200901T152702.620+04:00"
However when execute the search of createdDate the following error is displayed :
021-09-01 15:45:18.149 WARN 19588 --- [nio-9088-exec-1] .m.m.a.ExceptionHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.time.ZonedDateTime` from String "20210901T152702.620+04:00": Failed to deserialize java.time.ZonedDateTime: (java.time.format.DateTimeParseException) Text '20210901T152702.620+04:00' could not be parsed at index 0; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.time.ZonedDateTime` from String "20210901T152702.620+04:00": Failed to deserialize java.time.ZonedDateTime: (java.time.format.DateTimeParseException) Text '20210901T152702.620+04:00' could not be parsed at index 0e
Please find below my document:
public class Logging {
#Id
private String id;
#Field(type = FieldType.Text, name = "username")
private String username;
#Field(type = FieldType.Date, format = DateFormat.basic_date_time)
private ZonedDateTime createdDate = ZonedDateTime.now();
}
My request is shown below:
public class LoggingSearchCriteria extends AbstractSearchRequest {
private ZonedDateTime dateTo;
private ZonedDateTime dateFrom;
}
Any idea why I am getting this error when executing the search command?
Thnks in advance

spring jpa query is returning 404 no message [duplicate]

I'm trying to get all data of a user of a user with a timestamp:
#GetMapping("/datum/{userID}/{timeStamp}")
List<Datum> getDataSingleUserTimeRange(#PathVariable Long userID, #PathVariable LocalDateTime timeStamp)
{
....
}
Now to test this Spring Boot rest api, in postman, I made this call GET and url - http://localhost:8080/datum/2/2019-12-15T19:37:15.330995.
But it gives me error saying : Failed to convert value of type 'java.lang.String' to required type 'java.time.LocalDateTime'
How can I resolve this ??
You need #DateTimeFormat with custom pattern that matches to your input
#GetMapping("/datum/{userID}/{timeStamp}")
List<Datum> getDataSingleUserTimeRange(#PathVariable Long userID, #PathVariable #DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS") LocalDateTime timeStamp)
{
}
I don't know if it is the most modest way to do this or not, but here is what I have done :
#GetMapping("/datum/{userID}/{timeStamp}")
List<Datum> getDataSingleUserTimeRange(#PathVariable Long userID, #PathVariable String timeStamp)
{
DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
LocalDateTime dateTime = LocalDateTime.parse(timeStamp, formatter);
...
return datumRepository.findUsingTime(start,end);
}
Passed as string and parsed that. AnddateTime.truncatedTo(ChronoUnit.NECESARRY_UNIT); can be used as well.

Cannot insert date into the Oracle databe in Spring Boot via Thymeleaf

I have a typo in my CRUD process. I couldn't handle with inserting date type into the my database named for Oracle 11g.
When I try to insert data, there is an error appeared on the console.
Field error in object 'employee' on field 'registerDate': rejected value [2019-09-11]; codes [typeMismatch.employee.registerDate,typeMismatch.registerDate,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [employee.registerDate,registerDate]; arguments []; default message [registerDate]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'registerDate'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [#javax.validation.constraints.NotNull #javax.persistence.Temporal #javax.persistence.Column java.util.Date] for value '2019-09-11'; nested exception is java.lang.IllegalArgumentException]
How can I fix it?
Employee Forum
<form action="#" th:action="#{/employees/save}"
th:object="${employee}" method="POST">
...
<input type="date" name="date" th:field="*{registerDate}"
class="form-control mb-4 col-4" placeholder="Register Date">
</form>
Employee Object
#NotNull(message="is required")
#Temporal(TemporalType.DATE)
#Column(name="REGISTER_DATE")
private Date registerDate;
Controller Class
#PostMapping("/save")
public String saveEmployee(#ModelAttribute("employee") Employee theEmployee,#RequestParam("date") String date) throws IOException, ParseException {
// Date
SimpleDateFormat dateformat = new SimpleDateFormat("dd/MM/yyyy");
Date registerDate = dateformat.parse(String.valueOf(date));
System.out.println("/save | registerDate : " + registerDate);
theEmployee.setRegisterDate(registerDate);
// save the employee
employeeService.save(theEmployee);
}
Maybe you need to format the date for Oracle, for example:
#DateTimeFormat(pattern = "hh:mm aa")
#Column(name = "date_start")
private Date dateStart;

spring bind date field of command object

I have a form that inserts/updates data. The command object (Bean) class has a Date field that is placed in the form as follows:
<form:hidden path="createdDate">
when I submit the form, the BindResult.hasErrors() is validated as true.
I think I need to bind the date object, but how is it done for Command object field?
The form bean code is as follows
#Entity
#Table(name = "Employee")
public class Employee {
#Id
#GeneratedValue
#Column(name="id")
private int id;
#Column(name="EmployeeName")
private String employeeName;
#Column(name="CreatedDate")
private Date createdDate;
//Setter and getter methods
}
Error:
[Field error in object 'employee' on field 'CreatedDate': rejected value [Mon Sep 17 20:35:26 IST 2012]; codes [typeMismatch.employee.CreatedDate,typeMismatch.CreatedDate,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [subject.CreatedDate,CreatedDate]; arguments []; default message [CreatedDate]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'CreatedDate'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.util.Date] for property 'CreatedDate': no matching editors or conversion strategy found]]
Add this annotation to your date fields:
#Column(name="CreatedDate")
#DateTimeFormat(pattern="yyyy/MM/dd hh:mm:ss") //whatever format is appropriate to you..
private Date createdDate;
Ensure that you have joda time as a dependency and the library is present in classpath. It will automatically register a converter to take care of the transformation.
I found your problem. In your Employee model class the createdDate field is not defined correctly.
You need to use the #Temporal annotation to define that the field is of type date.
Please put the following annotation also on top of the field declaration of createdDate
#Temporal(TemporalType.TIMESTAMP)
I think this should solve your problem. Cheers.

Resources