0

i am not familiar as to how Spring JPA do caching on my queried database data.

Here is my scenario. I have a thread that always queries data from database. Then this database table data is updated from other module (i.e adding of data via REST-API request).

Now, my thread keeps on handling the same data every cycle, it does not get the updated data from database. Now, i have read that it caches the data but i do not know (or i have no idea) as to how to NOT cache it since i need the real time data.

Here is my source of the Thread. As seen below i am calling em.clear() as describe on other resources to clear the cache. However, it does not work.

Also tried moving em.clear() after getMyRepo() method call, but an error could not initialize proxy - no Session occurs.

Here is @Entity, Sorry i can't post the source as it has sensitive information. I just post the diagram indicating its relationship.

enter image description here

MyThread.java

@Component
@Transactional
@Scope("prototype")
public class MyThread implements Runnable {
    private static final Logger logger = LoggerFactory.getLogger(MyThread.class);

    private long myRepo_id;
    private boolean interrupt = false;

    @Autowired
    private MyProperties prop;

    @Autowired
    MyRepoRepository repo;

    @PersistenceContext
    private EntityManager em;

    @Override
    public void run() {
        while (!interrupt) {
            try {
                MyEntity entity = getMyRepo(myRepo_id);
                
                entity.stream().forEach(entry -> {
                    logger.info("This is my updated data from db: {}", entry.getMessage());
                });
                
                em.clear();
                
                Thread.sleep(prop.getProcessingInterval());
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                logger.error("Error Occured");
            } catch (Exception e) {
                logger.error("Error Occured");
            }
        }
    }

    private MyRepo getMyRepo(long id) {
        return repo.findById(id).get();
    }

    public void interrupt() {
        this.interrupt = true;
    }

    public void setMyRepoId(long myRepo_id) {
        this.myRepo_id = myRepo_id;
    }
}

AppEventConfiguration.java

@Configuration
public class AppEventConfiguration {
    private static final Logger logger = LoggerFactory.getLogger(AppEventConfiguration.class);
        
    @Autowired
    private ApplicationContext context;
    
    @Autowired
    @Qualifier("myThread")
    private TaskExecutor executor;
    
    @EventListener(ApplicationReadyEvent.class)
    public void onApplicationReadyEvent() {
        MyThread t = this.context.getBean(MyRunnableThread.class);
        t.setMyId(dto.getId());
        executor.execute(t); 
    }
}
lemoncodes
  • 2,371
  • 11
  • 40
  • 66

0 Answers0