2

There is a table in DB(Oracle) which stores "code" and its "Description". I need to load this table data during my application startup and store it in a variable (probably a Map object) so that I can look up the description of the code for each request without hitting the DB for every request. What would be the best way to do this?

Application is a standalone Java application based on Spring framework.

Thanks.

4
  • Same way you perform all your other queries to the database. Which part is troubling you? --- Also, you might want to consider lazy loading, i.e. to not query the database until you need a description the first time. Commented Sep 12, 2016 at 7:37
  • well, the answer could be a bit complex, you can handle this in two ways "JDBC" and "Hibernate", we need more informations to answer properly. take a look on "Prepared statement JDBC" probably is the easiest way then you can populate a map object from the prepared statement Commented Sep 12, 2016 at 7:38
  • Yes. I ll query the DB to fetch those data. I was looking more on the Spring configuration side to do this. Should I declare a bean and define a init-method which queries the DB and loads the data? or Is there any other better way to do this? Thanks. Commented Sep 12, 2016 at 7:52
  • @Kishore check my solution Commented Sep 12, 2016 at 11:22

2 Answers 2

1

You can create a class that picks application startup method. In spring you can implement ApplicationListener interface with ApplicationReadyEvent event.

At this point your application is ready to communicate with database and will execute your code automatically.

@Component
public class AppBootstrapListener implements ApplicationListener<ApplicationReadyEvent> {

    //Inject Service or repository if you have.

    /**
    * Executes on application ready event
    * Check's if data exists & calls to create or read data
    */
    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        // code here
    }

}

For any clearification add a comment

Sign up to request clarification or add additional context in comments.

Comments

0

Im not sure, but Spring events might help. For example, you can use ContextRefreshedEvent - this event is published whenever the Spring Context is started or refreshed.

Please check: running-code-on-spring-boot-startup or better-application-events-in-spring-framework-4-2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.