Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scheduled database maintenance with Java EE 6 (connection lifetime)

I'm new to Java EE 6 so I apologize if the answer to this question is obvious. I have a task that must run hourly to rebuild a Solr index from a database. I also want the rebuild to occur when the app is deployed. My gut instinct is that this should work:

@Singleton
@Startup
public class Rebuilder {
  @Inject private ProposalDao proposalDao;
  @Inject private SolrServer  solrServer;

  @Schedule(hour="*", minute="0", second="0")
  public void rebuildIndex() {
    // do the rebuild here
  }
}

Since I'm using myBatis, I have written this producer:

public class ProposalSessionProvider {
  private static final String CONFIGURATION_FILE = "...";

  static {
    try {
      sessFactory = new SqlSessionFactoryBuilder().build(
        Resources.getResourceAsReader(CONFIGURATION_FILE));
    }
    catch (IOException ex) {
      throw new RuntimeException("Error configuring MyBatis: " + ex.getMessage(), ex);
    }
  }

  @Produces
  public ProposalsDao openSession() {
    log.info("Connecting to the database");
    session = sessFactory.openSession();
    return session.getMapper(ProposalsDao.class);
  }
}

So I have three concerns:

  1. What's the appropriate way to trigger a rebuild at deployment time? A @PostConstruct method?
  2. Who is responsible for closing the database connection, and how should that happen? I'm using myBatis which is, I believe, pretty ignorant of the Java EE lifecycle. It seems like if I use @Singleton the connections will never be released, but is it even meaningful to put @Startup on a @Stateless bean?
  3. Should the Rebuilder be a singleton or not? It seems like if it is not I couldn't use @PostConstruct to handle the initial rebuild or I'll get double rebuilds every hour.

I'm not really sure how to proceed here. Thanks for your time.

like image 845
Daniel Lyons Avatar asked Nov 13 '22 10:11

Daniel Lyons


1 Answers

I don't know myBatis but i can tell you than @Schedule job is transactional. Anyway i'am not sure that JTA managed transaction will apply here according to the way you retrieve the session.
Isn't there a way to retrieve a persistenceContext in MyBatis ?

For the trigger part IMHO @Startup will do the job properly and will need a singleton bean so. Anyway i'am not able to tell you which of the 2 methods you propose is the best one.

like image 51
Gab Avatar answered Nov 30 '22 23:11

Gab