0

I have a query where I'm getting column names from a DB. These column names won't change on a request or session basis. So, to avoid running useless queries on each request, I would like to run this query once when the application is deployed and then keep the results in a List<String> for rest of the lifecycle of the application (until its deployed again).

How can this be achieved so that I can use the final List<String> in my service layer?

If there is a better way to do this rather than tying running a query on deploy, then please suggest some other way.

Currently, I have this:

public List<String> fetchColNames (String tableName) {
    String query = "SELECT Upper(column_name) FROM information_schema.columns WHERE table_name = ?";
        List<String> cols = getJdbcTemplate().query(query, new Object[] {tableName}, new RowMapper<String>() {
           public String mapRow(ResultSet rs, int rowNum) throws SQLException {
               return rs.getString(1);
           } 
        });
    return cols;
} 
4

2 回答 2

1

您可以使您的方法Cachable

@Component
public class ColumnFetcher {
    @Cachable("columnNames")
    public List<String> fetchColNames (String tableName) {
        String query = "SELECT Upper(column_name) FROM information_schema.columns WHERE table_name = ?";
            List<String> cols = getJdbcTemplate().query(query, new Object[] {tableName}, new RowMapper<String>() {
               public String mapRow(ResultSet rs, int rowNum) throws SQLException {
                   return rs.getString(1);
               } 
            });
        return cols;
    } 
}

当然,您还必须启用缓存注释:

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:cache="http://www.springframework.org/schema/cache"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
    <cache:annotation-driven />
</beans>
于 2012-11-13T16:49:28.747 回答
0

您可以在beanpostconstruct的方法上使用注解configurable,它将在应用程序部署时执行。

于 2012-11-14T09:20:39.510 回答