Tapestry Run on Startup

Tapestry has an @Startup annotation that allows you to mark items in your AppModule to run them at startup.  Here is an example.  I needed an application to check to see if there are any users and if not, add one.  The code below does this. The only difficulty was getting Hibernate to commit the transaction. Tapestry uses a HibernateSessionManager.  Once I had a reference to this, I was able to commit the transaction.  The @CommitAfter annotation does not work within the AppModule.

@Startup
public static void createAdminUser(Session session, HibernateSessionManager hsm) {
  //figure out how many users are contained in the system
  int numberOfUserAccounts = session.createCriteria(User.class).list().size();
  //if there are no users, go ahead and create the admin user
  if(numberOfUserAccounts < 1) {
    User user = new User();
    user.setUsername("admin");
    user.setPassword("adminpassword");
    user.setRoles("user,admin");
    session.save(user);
    //commit the hibernate transaction
    hsm.commit();
  }
}

About 

Leave a Reply

Your email address will not be published. Required fields are marked *