title: Singleton vs Stateless beans in the architecture of a Java EE application
body: <p>A part of business logic at the core of my project has to perform a search on linked-data. Currently, I have implemented this part using a singleton session bean like this (SPARQL is a query language on RDF models which are constructed using linked data).</p>
  
  <pre><code>@Singleton
  @Startup
  public class SparqlEngine {
  
      @PostConstruct
      private void init() {
          // Initialiaze the model by connecting to the database
      }
  
      public ResultSet searchBySparql(String sparqlQuery) {
          // Perform the search on the model which is stored in the database
      }
  
      @PreDestroy
      private void cleanup() {
          // Close database connection
      }
  
  }
  </code></pre>
  
  <p>This EJB is exposed to the other parts of my application by another EJB named <code>SparqlEndpoint</code> which is responsible for converting the <code>ResultSet</code> to a more comfortable <code>SearchResult</code> object which contains the model in a string form with the syntax specified by the client, total number of results and other metadata. The <code>SparqlEndpoint</code> EJB is simply <code>@Stateless</code> and has a local interface which is used by the clients. These clients include JSF managed beans and a couple of EJBs which expose it as SOAP and RESTful web services.</p>
  
  <p>This is the most reasonable architecture that came to my mind, but I need to know if I have done it right. Should I use a <code>Singleton</code> bean to implement the core as I'm doing now, or a <code>Stateless</code> session bean is more appropriate? The database connection initialization usually takes a couple of seconds at least, and it may be useful to note than the it is a NoSQL one and does not support transactions. I'm not planning to add anything such as a write method to this bean. Is it correct for other EJBs to be stateless? If I want to expose my indexing engine (which performs writes on the database) as another EJB, how should I implement it?</p>
  
  <p>Thanks in advance.</p>