Spring JPA Equal conditon with derived query for LocalDate not working

Viewed 304

I have a Oracle DB with type of DATE my Entiy class have LocalDate parameter as shown in here

@Entity
@Table(name = "CONTRACT")
public class ContractEntity {
    private Long id;
    private LocalDate contractStartDate;
    private LocalDate contractEndDate;
    ...

For the testing I created derived query to find Entity by contractStartDate

public interface ContractRepository extends JpaRepository<ContractEntity, Long>, JpaSpecificationExecutor<ContractEntity> {
            ContractEntity getContractEntityByContractStartDateIs(LocalDate date)
}

Then I created Two Tests as follows;

 @DisplayName("Should get Exact Date  Entity")
    @Test
    void test1(){
        LocalDate date=LocalDate.of(2021,03,9);
        ContractEntity entity= searchService.getByDate(date); // getByDate is mapped to getContractEntityByContractStartDateIs() in service layer
        assertEquals(date,entity.getContractStartDate());
    }



    @DisplayName("Should match ID:1 Entity's Date with Local Date")
    @Test
    void test2(){
        ContractEntity entity=searchService.getById(1l).get(); 
        assertEquals(1l,entity.getId());
        LocalDate date=LocalDate.of(2021,03,9);
        assertEquals(date,entity.getContractStartDate());
    }

}

My problem is test1 fails with null error which means equality condition fails to give existence of that Entity even though test2 passed which date is equal to id:1 entity's Start-date

p.s: I have set Contract Table's ID:1 Contract Start Date value to 2021,03,9 as shown in image here enter image description here

So what would be the reason for this Why test1 fails to get equal entity and why test2 pass that assert equity of date is true

1 Answers

LocalDate doesn't contain a time component, but the data type you used in the database does and it is not 0 for the data in the database.

In order to make the comparison (which happens in the database) the LocalDate gets converted with a date + time where the time is probably 0, which is not equal to the date+times present in the database.

When the entity gets loaded the time part of the database value gets dropped and the result is equal to your LocalDate value.

Related