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

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;

Related

Searching the Records on basis of Date

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.

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

How to insert date type when integratting between Hibernate and Spring

I 'm using Hibernate framework as way of mapping from Javabean to Database for my project which applied by Spring framework.But, I don' know how to insert Date type in Hibernate
My code :
User class:
import java.util.Date;
......................................
#Column(name = "date")
private Date date;
#SuppressWarnings("deprecation")
public void setDate(String date) {
Date date1 = new Date(date);
this.date = date1;
}
My register.jsp
<tr>
<td><form:label path="date">Date</form:label></td>
<td><form:input path="date" /></td>
</tr>
After submitting.date fileds in databse is null. It's value can not be mapped into Account table in database
Note: Account means :
#Entity
#Table(name="Account")
public class User {
Please help me.Thanks
I also has this problem.When I insert date type object into DB,it turns out null value.
My date type in DB is Datetime type.In my case,it is format problem.
Then I try to do so,then solved it,after following formatting.
Date date=new Date();
SimpleDateFormat spl=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String d=spl.format(date);
date=spl.parse(d);
You can try it.
in your User class use the following to map the column as date type
#Column(name = "date")
#Temporal(TemporalType.DATE)
private Date date;

How to display Spring MVC form errors for class error

I'm familiar with using Spring's <form:errors> tags to display validation errors for object properties, but how do you display an error at the class level?
Here's an example of what I'm talking about:
#ScriptAssert(lang = "javascript",
script = "_this.isExistingEmployee == true || (_this.phoneNumber != null && _this.address != null)",
message = "New hires must enter contact information")
public class JobApplicationForm {
#NotBlank(message = "First Name is required")
private String firstName;
#NotBlank(message = "Last Name is required")
private String lastName;
#NotNull(message = "Please specify whether you are an existing employee in another area")
private Boolean isExistingEmployee;
private String phoneNumber;
private String address;
}
#ScriptAssert here just confirms that if the applicant has indicated that they are an existing employee they can skip the contact info, but if not they must enter it. When this validation fails, the error is not on a given field but rather is on the class.
Within the form, I can show an error on a field with <form:errors path="firstName"> and I can display all errors (class and field) at once using <form:errors path="*"> but how can I isolate and display class level errors?
To show only class-level errors, leave the path empty.
<form:errors path="">
from the Spring docs:
path="*" - displays all errors
path="lastName" - displays all errors associated with the lastName field
if path is omitted - object errors only are displayed
ref: http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/view.html#view-jsp-formtaglib-errorstag

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