mysql – How to create the tables when starting the System with JSF and JPA?

Question:

Guys, how do I get the tables created automatically when the system starts? The way my system is, the tables are only created when some kind of access to the database is done. For example, in the login screen, just press the login button and the tables are created. My intention is that they are created when starting the system.

I'm using JPA + JSF + MySql

Answer:

In your case I would create a class that implements ServletContextListener which is a Listener that checks when the beginning and end of an application, when implementing this class two superscript methods are created: contextInitialized() and contextDestroyed() .

In the contextInitialized() method you start what you want along with the server, for example:

@Override
public void contextInitialized(ServletContextEvent sce) {
    emf = Persistence.createEntityManagerFactory(pu);
    System.out.println("Contexto Inicializado");
}

And in the contextDestroyed() method you put everything you want to finish with the server, for example:

@Override
public void contextDestroyed(ServletContextEvent sce) {
   emf.close();
}

Finally, just register the Listener in web.xml

<listener>
  <listener-class>com.util.suaclasse</listener-class>
</listener>
Scroll to Top
AllEscort