Maxx
Maxx

Reputation: 11

How is possible that Spring cache return modified object?

i have this test:

@Test
    public void testCacheLineOfCredit() throws Exception {
        LineOfCreditInfo created = repository.save(this.getInfo());
        assertThat(created, is(notNullValue()));

        //First fetch read from DB
        LineOfCreditInfo firstSearch = service.fetch(created.getId());
        System.out.println("Created ID: " + created.getId() + " Date: " + created.getStartDate().toString());
        System.out.println("First ID:   " + firstSearch.getId() + " Date: " + firstSearch.getStartDate().toString());
        assertEquals(created.getStartDate(), firstSearch.getStartDate());
        Thread.sleep(100);
        LineOfCreditInfo updated = this.getInfo();
        updated.setId(created.getId());
        updated.setAgreement(created.getAgreement());
        repository.save(updated);

        //Second fetch read from cache
        LineOfCreditInfo secondSearch = service.fetch(created.getId());
        System.out.println("---------------------------------------");
        System.out.println("Updated ID: " + created.getId() + " Date: " + created.getStartDate().toString());
        System.out.println("Second ID:  " + secondSearch.getId() + " Date: " + secondSearch.getStartDate().toString());

    }

Well the output of the System.out is this:

Object read from database
Created ID: c7e635c6-6024-4149-9f92-74316c149800 Date: 2020-02-25T16:22:01.181+01:00[Europe/Berlin]
First ID:   c7e635c6-6024-4149-9f92-74316c149800 Date: 2020-02-25T16:22:01.181+01:00[Europe/Berlin]
---------------------------------------
Updated ID: c7e635c6-6024-4149-9f92-74316c149800 Date: 2020-02-25T16:22:01.464+01:00[Europe/Berlin]
Second ID:  c7e635c6-6024-4149-9f92-74316c149800 Date: 2020-02-25T16:22:01.464+01:00[Europe/Berlin]

How is possible that the second Id Date is equal at the updated object if this is read from cache?

In the service there's a system.out that write only in the first fetch, correctly.

This is the service method:

@Cacheable(value = "lineOfCredits")
    public LineOfCreditInfo fetch(String id) throws ContextOutOfDomainException {
        InvoiceFinancingContext context = contextFactory.getObject();
        log.info(String.format("Object read from database: Id[%s]", id));

        Optional<LineOfCreditInfo> lineOfCreditInfo = repository.findByIdAndDomainId(id, context.getDomainId());
        System.out.println("Object read from database");
        return lineOfCreditInfo.get();
    }

Upvotes: 1

Views: 67

Answers (1)

Alejandro Venegas
Alejandro Venegas

Reputation: 249

I think you tried to print here the "updated" object :

System.out.println("Updated ID: " + updated.getId() + " Date: " + updated.getStartDate().toString());

And not the "created" in the "Updated ID" like your current code :

 System.out.println("Updated ID: " + created.getId() + " Date: " + created.getStartDate().toString());

Upvotes: 1

Related Questions