public class Database 
{
    private static DataSource dataSource;

    static 
    {
        try 
        {
          dataSource = new InitialContext().lookup("jndifordbconc");
        }catch (NamingException e) 
        { 
          throw new ExceptionInInitializerError("'jndifordbconc' not found in JNDI", e);
        }
    }

    public static Connection getConnection() 
    {
      return dataSource.getConnection();
    }
}

public List<Entity> list() throws SQLException 
{
    Connection        connection = null;
    PreparedStatement statement  = null;
    ResultSet         resultSet  = null;
    List<Entity>      entities   = new ArrayList<Entity>();

    try 
    {
        connection = Database.getConnection();
        statement  = connection.prepareStatement("SELECT id, foo, bar FROM entity");
        resultSet  = statement.executeQuery();

        while (resultSet.next()) 
        {
            Entity entity = new Entity();
            entity.setId(resultSet.getLong("id"));
            entity.setFoo(resultSet.getString("foo"));
            entity.setBar(resultSet.getString("bar"));
            entities.add(entity);
         }
    } 
    finally 
    {
        if (resultSet  != null) try { resultSet.close();  } catch (SQLException ignore) {}
        if (statement  != null) try { statement.close();  } catch (SQLException ignore) {}
        if (connection != null) try { connection.close(); } catch (SQLException ignore) {}
    }
    return entities;
}

Leave a reply