Java Date field not shown properly in postman - spring-boot

Any help or hint would be greatly appreciated it!!
I am using Spring Boot 2.56
The date and time show properly for field "transactionDate" field when debugging the code in intellij.
2023-01-15 23:35:05.0
enter image description here
Code:
public List < TransactionEntity > findByFromAccountIdOrToAccountId(Long accountId) {
AccountEntity account = accountRepository.findByAccountId(accountId);
if (account == null) {
throw new AccountException("account cannot be found in account table accountId:" + accountId);
}
List < TransactionEntity > list = transactionRepository.findByFromAccountOrToAccount(account, account);
return list;
}
TransactionEntity.java
private Timestamp transactionDate;
For the transactionDate field I used import java.sql.Timestamp;
In postman it is showing: "transactionDate": 1673843714000,
How can I show the proper date and time in postman result such as "2023-01-15 23:35:05.0".

"transactionDate": 1673843714000
This is how Timestamp looks like. If you want to show like you mention use LocalDateTime instead.
private LocalDateTime transactionDate;
Or convert
transactionDate.toLocalDateTime().toLocalDate()

Related

How to pass 2 or more variables using #PathParam in spring mvc? and suppose if I want to test it out using postman how to do that?

I'm trying to fetch value from db using JPA repository method
product findByIdNumberOrCifNumber(String idNumber , String cifNumber);
service class logic:-
public ResponseModel FindByCivIDOrCifNumber(String idNumber,String cifNumber) {
ResponseModel responseModel = new ResponseModel();
Optional<product> civId = Optional.ofNullable(productRepos.findByIdNumber(idNumber));
if (civId.isPresent()) {
responseModel.setResponse(productRepos.findByIdNumberOrCifNumber(idNumber,cifNumber));
} else {
errorModel errorModel1 = new errorModel();
enter image description here errorModel1.setErrorCode(productConstant.INVALID_REQUEST);
errorModel1.setErrorDescription("Requested Civil Id or CifNUmber is not present");
responseModel.setErrorModel(errorModel1);
}
return responseModel;
}
controller class:-
#GetMapping("/getByCifNoOrGetByIdNo")
public ResponseModel getProductByCifNoOrGetByIdNo(#RequestParam String idNumber,#RequestParam String cifNumber ) {
return productService.FindByCivIDOrCifNumber(idNumber,cifNumber);
}
post man:-
kindly help me out how to make it work:)
If you are looking for an answer to pass two or more path variables and test it with postman, you can try this.
#GetMapping("/api/mapping-name/{variable1}/{variable2}")
Here you will be getting two path variables which you can access by the syntax
#PathVariable("variable1") datatype variableName
Now in postman request url you can simply give the respective url, lets say:
https://localhost8080/api/mapping-name/:variable1/:variable2
which automaticaly will give you a key value section in the path variables section in the params with prepopulated key names as per the name you have given. In this case variable1 & variable2.
Give the respective value and it should work.

findByDate returning documents from previous day

I'm trying to fetch a list of objects by date, but the resulted list is always of the day before.
#GetMapping("date")
ResponseEntity findByDate(#RequestParam #DateTimeFormat(pattern = "yyyy-MM-dd") Date date) {
log.info("date is: "+date);
log.info("Delfaul time zone is: "+ TimeZone.getDefault());
return ResponseEntity.ok(consumptionService.findByDate(date));
}
the controller calls the service, which calls HourlyConsumptionRepo:
public interface HourlyConsumptionRepo extends MongoRepository<HourlyConsumption, ObjectId> {
List<HourlyConsumption> findByDate(Date date);
}
Postman results
Postman results
I think it might be an issue of timezones, but I can't figure out how to fix it.
MongoDB uses UTC times by default. See here: https://www.mongodb.com/docs/v3.2/tutorial/model-time-data/. So those results are "valid", I'm assuming you are UTC+2.

InvalidPathException while sorting with org.springframework.data.domain.Pageable

I am trying to sort my table's content on the backend side, so I am sending org.springframework.data.domain.Pageable object to controller. It arrives correctly, but at the repository I am getting org.hibernate.hql.internal.ast.InvalidPathException. Somehow the field name I would use for sorting gets an org. package name infront of the filed name.
The Pageable object logged in the controller:
Page request [number: 0, size 10, sort: referenzNumber: DESC]
Exception in repository:
Invalid path: 'org.referenzNumber'","logger_name":"org.hibernate.hql.internal.ast.ErrorTracker","thread_name":"http-nio-8080-exec-2","level":"ERROR","level_value":40000,"stack_trace":"org.hibernate.hql.internal.ast.InvalidPathException: Invalid path: 'org.referenzNumber'\n\tat org.hibernate.hql.internal.ast.util.LiteralProcessor.lookupConstant(LiteralProcessor.java:111)
My controller endpoint:
#GetMapping(value = "/get-orders", params = { "page", "size" }, produces = { MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<PagedModel<KryptoOrder>> getOrders(
#ApiParam(name = "searchrequest", required = true) #Validated final OrderSearchRequest orderSearchRequest,
#PageableDefault(size = 500) final Pageable pageable, final BindingResult bindingResult,
final PagedResourcesAssembler<OrderVo> pagedResourcesAssembler) {
if (bindingResult.hasErrors()) {
return ResponseEntity.badRequest().build();
}
PagedModel<Order> orderPage = PagedModel.empty();
try {
var orderVoPage = orderPort.processOrderSearch(resourceMapper.toOrderSearchRequestVo(orderSearchRequest), pageable);
orderPage = pagedResourcesAssembler.toModel(orderVoPage, orderAssembler);
} catch (MissingRequiredField m) {
log.warn(RESPONSE_MISSING_REQUIRED_FIELD, m);
return ResponseEntity.badRequest().build();
}
return ResponseEntity.ok(orderPage);
}
the repository:
#Repository
public interface OrderRepository extends JpaRepository<Order, UUID> {
static final String SEARCH_ORDER = "SELECT o" //
+ " FROM Order o " //
+ " WHERE (cast(:partnerernumber as org.hibernate.type.IntegerType) is null or o.tradeBasis.account.retailpartner.partnerbank.partnerernumber = :partnerernumber)"
+ " and (cast(:accountnumber as org.hibernate.type.BigDecimalType) is null or o.tradeBasis.account.accountnumber = :accountnumber)"
+ " and (cast(:orderReference as org.hibernate.type.LongType) is null or o.tradeBasis.referenceNumber = :orderReference)"
+ " and (cast(:orderReferenceExtern as org.hibernate.type.StringType) is null or o.tradeBasis.kundenreferenceExternesFrontend = :orderReferenceExtern)"
+ " and (cast(:dateFrom as org.hibernate.type.DateType) is null or o.tradeBasis.timestamp > :dateFrom) "
+ " and (cast(:dateTo as org.hibernate.type.DateType) is null or o.tradeBasis.timestamp < :dateTo) ";
#Query(SEARCH_ORDER)
Page<Order> searchOrder(#Param("partnerernumber") Integer partnerernumber,
#Param("accountnumber") BigDecimal accountnumber, #Param("orderReference") Long orderReference,
#Param("orderReferenceExtern") String orderReferenceExtern, #Param("dateFrom") LocalDateTime dateFrom,
#Param("dateTo") LocalDateTime dateTo, Pageable pageable);
}
Update:
I removed the parameters from the sql query, and put them back one by one to see where it goes sideways. It seems as soon as the dates are involved the wierd "org." appears too.
Update 2:
If I change cast(:dateTo as org.hibernate.type.DateType) to cast(:dateFrom as date) then it appends the filed name with date. instead of org..
Thanks in advance for the help
My guess is, Spring Data is confused by the query you are using and can't properly append the order by clause to it. I would recommend you to use a Specification instead for your various filters. That will not only improve the performance of your queries because the database can better optimize queries, but will also make use of the JPA Criteria API behind the scenes, which requires no work from Spring Data to apply an order by specification.
Since your entity Order is named as the order by clause of HQL/SQL, my guess is that Spring Data tries to do something stupid with the string to determine the alias of the root entity.

DB field empty problems in Spring Boot

I have a method in Spring Boot that collects various database dates from the logged in employee.
private boolean isActiveThisMonth(EmployeeView emp,LocalDate date){
return (emp.getHiringDate().withDayOfMonth(1).minusDays(1).isBefore(date.withDayOfMonth(1)) && (emp.getLeavingDate()==null ||
emp.getLeavingDate().plusMonths(1).withDayOfMonth(1).isAfter(date.with(lastDayOfMonth()))));
}
Currently if the hiringDate field is empty in the database, it returns an error. How can I add an exception so that if the field arrives without an error? Or if it is better to put a date, for example the current day and thus not an error?
A couple of ways to prevent this.
1.
You could handle the null value inside isActiveThisMonth like this
private boolean isActiveThisMonth(EmployeeView emp,LocalDate date){
LocalDate hiringDate = emp.getHiringDate() != null ? emp.getHiringDate() : LocalDate.now();
return (hiringDate.withDayOfMonth(1).minusDays(1).isBefore(date.withDayOfMonth(1)) && (emp.getLeavingDate()==null ||
emp.getLeavingDate().plusMonths(1).withDayOfMonth(1).isAfter(date.with(lastDayOfMonth()))));
}
You could make sure the value is set in the Entity when the Employee is created.
#Column(name = "hire_date", columnDefinition = "DATE DEFAULT CURRENT_DATE")
private jDate startDate;

Spring Mongodb query for Employee first and last name and dob using range criteria

I have some data on employees which stores typical information like first and last name and dob, etc... The business case I have been given requires me to pull a record for an employee based on a criteria of first name, last name and dob.
At first I thought this would be easy, but after doing a search in db, I found the dob records have differing timestamps (which doesn't make sense). Without getting into the internal company issues of addressing this, I need my query to look at a dob with a start of day and end of day range.
My sample code below demonstrates my latest effort to solve this issue but have not been able to match results with what i see in the db. This code is using Spring Mongodb Query and mongoDbTemplate for constructing the queries. I could really use some help in figuring this one out.
I have to set a date range to ensure I get the employee for that day but can't figure out how to construct the query correctly.
sample method:
#Slf4j
#Repository
public class EmployeeDao {
private static final int START_OF_DAY = 0;
private static final int END_OF_DAY = 1;
#Getter private MongoTemplate mongoTemplate;
#Autowired
public void setMongoTemplate(MongoTemplate mongoTemplate) {
DB db = mongoTemplate.getDb();
mongoTemplate = new MongoTemplate(db.getMongo(), "EmployeeDB");
this.mongoTemplate = mongoTemplate;
}
public List<Employee> findEmployeeByNameIdDobRange(String lName, String fName, Date dob){
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
String startFmt = df.format(convertTo(dob, START_OF_DAY));
String endFmt = df.format(convertTo(dob, END_OF_DAY));
Query q = new Query();
q.addCriteria(Criteria.where("employee.firstName").regex(fName, "i")
.and("employee.lastName").regex(lName, "i")
.andOperator(
Criteria.where("employee.dob").gte(startFmt).lte(endFmt)
)
);
return return getMongoTemplate().find(q, Employee.class);
}
private Date convertTo(Date dt, int startOrEnd){
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
switch (startOrEnd) {
case END_OF_DAY:
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
cal.set(Calendar.MILLISECOND, 999);
break;
case START_OF_DAY:
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 1);
cal.set(Calendar.SECOND, 1);
cal.set(Calendar.MILLISECOND, 1);
break;
default:
throw new IllegalArgumentException("starOrEnd paramter does not equal 0 for beggining or 1 for end of day");
}
log.info(cal.toString());
return cal.getTime();
}
I appreciate any suggestions that can be made. Thanks!

Resources