Devendra Singh
Devendra Singh

Reputation: 11

How can we cache the MySQL query on the server side running java web application?

Example: If most clients require to fill the form which require selection of states and cities. So how could this query can be cached on the server side. Because the state or the city name hardly changes, so its good idea to cache them.

Table 1:
state_name  state_id
__________  ________
state1         1
state2         2

Table 2:
city_name   city_id   state_id
_________   _______   ________
city1          1         1
city2          2         1
city3          3         2

Upvotes: 0

Views: 1149

Answers (2)

Adam
Adam

Reputation: 480

Mysql by default will cache queries in its query cache - http://dev.mysql.com/doc/refman/5.1/en/query-cache.html

The cache of course has a finite size and so the results can be evicted if other queries are run - but if this query is executed frequently the mysql query cache may be sufficient for your needs.

Upvotes: 1

duffymo
duffymo

Reputation: 308733

Create a List<String> of states and a Map<String, String> of [ city, state ] pairs and put it on the server as static, read-only data. Load it from the database on startup.

I'd recommend a WeakHashMap as your implementation. It'll give the GC a chance to evict values if absolutely necessary.

Number of states won't change, but cities list could be rather large.

Upvotes: 3

Related Questions