Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 1035203
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T14:30:33+00:00 2026-05-16T14:30:33+00:00

NOTE: Please ignore my use of MultivaluedMap instead of multiple vargs String…args . Is

  • 0

NOTE: Please ignore my use of MultivaluedMap instead of multiple vargs String…args.

Is there a standard way in java of doing this?

What I have is a resource, that is returned from a remote server. But before each query, the remote connection must be open, and after the returns are returned – it must be closed.

So a natural way of doing this is something like:

Connection c = config.configureConnection();
c.open();       //open
List<Car> cars;
try{
   cars = c.getCars();
}finally{
   c.close();   //close
}

Now I want to implement something that operates on the level of the resources themselves, without worrying about connection, for example:

List<Car> cars = new CarResource().all(); //opens and closes connection

The way I am currently doing it is by having one abstract class, AbstractQueriable call abstract methods query(String …args) and query(int id), which any class extending it must implement.

The AbstractQuerieable implements the Queriable interface, which makes it expose the three public methods filter(String …args), all() and get(int id) – which are the public facing methods.

Here is the Queriable interface:

public interface Queriable <T>{
    public T get(String id);
    /** Simply returns all resources */
    public Collection<T> all(); 
    public Collection<T> filter(MultivaluedMap<String, String> args);   
}

here is the AbstractQueriable class that implements it:

public abstract class AbstractQueriable<T> implements Queriable<T> {

@Override
public final T get(String id) {
    setup();
    try {
        return query(id);
    } finally {
        cleanup();
    }
}

@Override
public final Collection<T> filter(MultivaluedMap<String, String> args) {
    setup();
    try {
            return query(args);
    } finally {
        cleanup();
    }
}

/**
 * Returns all resources.
 * 
 * This is a convenience method that is equivalent to passing an empty
 * arguments list to the filter function.
 * 
 * @return The collection of all resources if possible
 */
    @Override
public final Collection<T> all() {      
    return filter(null);
}

/**
 * Queries for a resource by id.
 * 
 * @param id
 *            id of the resource to return
 * @return
 */
protected abstract T query(String id);

/**
 * Queries for a resource by given arguments.
 * 
 * @param args
 *            Map of arguments, where each key is the argument name, and the
 *            corresponing values are the values
 * @return The collection of resources found
 */
protected abstract Collection<T> query(MultivaluedMap<String, String> args);

private void cleanup() {
    Repository.close();
}

private void setup() {
    Repository.open();
}

and finally my resource, which I want to use in the code, must extend the AbstractQueriable class, for example (please note that the details of these methods are not important):

public class CarRepositoryResource extends AbstractQueriable<Car> {

    @Override
    protected Car query(String id) {
        MultivaluedMap<String, String> params = new MultivaluedMapImpl();
        params.add("CarID", id);

        // Delegate the query to the parametarized version
        Collection<cars> cars = query(params);
        if (cars == null || cars.size() == 0) {
            throw new WebApplicationException(Response.Status.NOT_FOUND);
        }
        if (cars.size() > 1) {
            throw new WebApplicationException(Response.Status.NOT_FOUND);
        }
        return cars.iterator().next();
    }

    @Override
    protected Collection<Car> query(MultivaluedMap<String, String> params) {
        Collection<Car> cars = new ArrayList<Car>();        

        Response response = Repository.getConnection().doQuery("Car");
        while (response.next()) {
            Returned returned = response.getResult();
            if (returned != null) {
                cars.add(returned);
            }
        }
        return cars;
    }

}

which finally, I can use in my code:

Collection<Car> cars = new CarRepositoryResource().all();
//... display cars to the client etc...

There are a few things I don’t like about this kind of setup:

  1. I must instantiate a new instance of my “CarRepositoryResource” every time I do a query.
  2. The method names “query”, while internal and private, are still confusing and clunky.
  3. I am not sure if there is a better pattern or framework out there.

The connection that I am using does not support/implement the JDBC api and is not sql-based.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-16T14:30:33+00:00Added an answer on May 16, 2026 at 2:30 pm

    You could use a variation of the (in)famous Open session in view pattern.

    Basically it comes down to this:

    1. Define a “context” in which connections are available
      (usually the request in web applications)
    2. Handle (possibly lazy) initialization and release of a connection when entering/exiting the context
    3. Code your methods taking for granted they will only be used inside such a context

    It is not difficult to implement (storing the connection in a static ThreadLocal to make it thread safe) and will definitely spare a few open/close calls (performance-wise that could be a big gain, depending on how heavy your connection is).

    The context class could look something like (consider this pseudo-code);

    public class MyContext{
      private static final
      ThreadLocal<Connection> connection = new ThreadLocal<Connection>();
    
      public static void enter() {
         connection.set(initializeConnection());
         // this is eager initialization
         // if you think it will often the case that no connection is actually
         // required inside a context, you can defer the actual initialization
         // until the first call to get()
      }
    
      public static void exit() {
        try { connection.close(); }
        catch(Throwable t) { /* panic! */ }
        finally { connection.set(null); }
      }
    
      public static Connection get() {
        Connection c = connection.get();
        if (c == null) throw new IllegalStateException("blah blah");
        return c;
      }
    }
    

    Then you would use connections like this:

    MyContext.enter();
    try {
       // connections are available here:
       // anything that calls MyContext.get()
       // gets (the same) valid connection instance
    } finally {
      MyContext.exit();
    }
    

    This block can be put wherever you want (in webapps it usually wraps the processing of each request) – from the main method if you are coding a simple case when you want a single connection available for the whole lifespan of your application, to the finest methods in your API.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Please note - I am not looking for the right way to open/read a
Please note the Edit below for a lot more information, and a possible solution
Please note: In each step I describe below I'm logged in as the same
How do I print debug messages in the Google Chrome JavaScript Console? Please note
NOTE: XMLIgnore is NOT the answer! OK, so following on from my question on
Note: This was posted when I was starting out C#. With 2014 knowledge, I
NOTE: I am not set on using VI, it is just the first thing
Note: Originally this question was asked for PostgreSQL, however, the answer applies to almost
Note that I am not asking which to choose (MVC or MVP), but rather
Note : The code in this question is part of deSleeper if you want

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.