如果未找到数据库,如何编写异常以允许应用程序 运行?

How to write an exception to allow application to run if database is not found?

我目前有一个 jdbcUrl oracle 数据库绑定到我的 cloud foundry 应用程序。我希望我的应用程序能够构建 运行 即使服务未绑定。这意味着它会抛出一个空异常,但仍然允许应用程序 运行。 (只是不会显示任何数据)。

SQLREPO

@Repository
public class myTableRepo {

    @Autowired
    JdbcTemplate jdbcTemplate;

     @Transactional(readOnly=true)
    public List<myTable_Model> getAll(String id) {

        String sql = "SELECT * from myTable order by last_modified desc";

        return jdbcTemplate.query(sql, 
                new myTableRowMapper());
   }
    }

RowMapper class

class myTableRowMapper implements RowMapper<myTable_Model>
{
    @Override
    public myTable_Model mapRow(ResultSet rs, int rowNum) throws SQLException {
        myTable_Model model = new myTable_Model();

        model.setId(rs.getString("id"));
        model.setName(rs.getString("name"));
        model.setlast_modified(rs.getString("last_modified"));

        return model;
    }
}

如果找不到数据库,我将如何编写异常。抓住它并继续我的申请?

您只能捕获与 SQL 连接相关的异常,然后将其记录下来。

@Transactional(readOnly=true)
 public List<myTable_Model> getAll(String id) {
   List<myTable_Model> result = new ArrayList<>();
   try {
       String sql = "SELECT * from myTable order by last_modified desc";
       result = jdbcTemplate.query(sql, new Clone_HistoryRowMapper());
   }
   catch(SQLException ex) {
      logger.log("An error happened when interacting to the database.", ex)
   }
   return result;
 }

这样,如果发生仅与 SQL 相关的错误并停止 id 发生其他错误,应用程序将继续。

您似乎在使用 Spring,因此我建议您查看个人资料。

https://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-definition-profiles

使用配置文件,您可以为不同的环境配置一组不同的 bean。例如,您可以配置一个运行和配置内存数据库的 "local" 配置文件,并且可以为您的应用程序在 Cloud Foundry 上 运行 时配置一个 "cloud" 配置文件。当您将应用程序部署到 Cloud Foundry 时,Java 构建包将自动激活 "cloud" 配置文件(这也可以在没有 CF 的情况下工作,您只需手动启用配置文件)。启用配置文件的说明在此处。

https://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-definition-profiles-enable

Spring Boot 使启用配置文件 even easier. It also allows you to configure conditional beans,例如,如果 bean A 不存在则配置 X。这样你可以有一个默认的内存数据库,如果不存在则配置其他数据源已配置。