Hello, I have a small table that I want to load into memory in the form of List<Country> , so as not to pull the database. But ... how to do it right?

DataSource is:

 @Configuration public class DataSourceConfig { @Value("${jdbc.url}") private String url; @Value("${jdbc.username}") private String username; @Value("${jdbc.password}") private String password; @Bean public DataSource dataSource() { HikariDataSource dataSource = new HikariDataSource(); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setJdbcUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); dataSource.setMaximumPoolSize(10); return dataSource; } @Bean public Sql2o sql2o() { return new Sql2o(dataSource()); } } 
  • What's the problem? You declare a bin in the constructor that rakes the data from the database to the collection field and makes all subsequent references to the data through the methods of this bin. - Sergey Gornostaev

1 answer 1

I usually do it this way:

I create a bin-holder with a collection / map of objects, in the @PostConstruct method @PostConstruct unload the necessary data from the database, and I implement the necessary get methods.

Pseudo Java code:

 @Component public class CountryHolder { @Inject/@Autowired private Dao/DataSource dao/dataSource; private Map<String, Country> countries; //ΠΊΠ»ΡŽΡ‡, Π½Π°ΠΌΠΏΡ€ΠΈΠΌΠ΅Ρ€, Π½Π°Π·Π²Π°Π½ΠΈΠ΅ страны @PostConstruct private void initCountries(){ //Π’Ρ‹Π³Ρ€ΡƒΠΆΠ°Π΅ΠΌ ΠΈΠ· Π½ΡƒΠΆΠ½ΠΎΠΉ Ρ‚Π°Π±Π»ΠΈΡ†Ρ‹ Π΄Π°Π½Π½Ρ‹Π΅, ΠΈΠ½ΠΈΡ†ΠΈΠ°Π»ΠΈΠ·ΠΈΡ€ΡƒΠ΅ΠΌ countries } /* ... ...//Π½Π΅ΠΎΠ±Ρ…ΠΎΠ΄ΠΈΠΌΡ‹Π΅ ΠΌΠ΅Ρ‚ΠΎΠ΄Ρ‹ для Ρ€Π°Π±ΠΎΡ‚Ρ‹ ... */ } 

later in the code, you can inject this bin and use it as intended

 @Inject private CountryHolder countryHolder; ... ... countryHolder.getCountries(); ... ...