How do I insert pre-registered records into the system with jsf and jpa. I want it when the system starts the admin user is created.
How do I insert pre-registered records into the system with jsf and jpa. I want it when the system starts the admin user is created.
You can use the @PostConstruct annotation in the method of your managedBean. This annotation will cause the method to be invoked after your mBean is instantiated.
Example:
@ManagedBean
@RequestScoped
public class TesteMBean{
private UserAdm userAdm;
@PostConstruct
public void init(){
userAdm = new UserAdm();
}
public UserAdm getUserAdm() {
return userAdm;
}
public void setUserAdm(UserAdm userAdm) {
this.userAdm = userAdm;
}
}
Another option is to implement a ServletContextListener and insert the records in the contextInitialized method , which is invoked when the server initializes the application context. That way you do not have to access the application for this first action (insert the records) to be executed.
And the ServletContextListener is managed by the application server, that is, you can access resources such as EntityManager.
@Inject
private EntityManager em;
In addition, if you use a Managed Bean JSF, the annotated method with @PostConstruct will run every time the corresponding jsf page loads, whereas the contextInitialized method will be loaded only once when the server starts the application.
@Override
public void contextInitialized(ServletContextEvent event) {
StringBuilder sb = new StringBuilder();
sb.append("Aplicação xyz iniciada: ");
sb.append(new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(Calendar.getInstance().getTime()));
System.out.println(sb.toString());
gravarRegistrosPreCadastrados(); //TODO
}
Daniel, complementing what Paulo Cardoso said, you can use @PostConstruct on a given Managed Bean and apply @ApplicationScoped, so it will run only once when you access the application.
@Named(value = "tarefasBean")
@ApplicationScoped
public class TarefasBean implements Serializable {
public TarefasBean() {
System.out.println("INICIANDO TAREFAS BEAM");
}
@PostConstruct
public void executarTarefas() {
verificarConexão();
iniciarQuartz();
}
private void iniciarQuartz() {
//iniciando agenda de tarefas aki
}
public void verificarConexão() {
//meu codigo aki
}
}
In the method checks connection, in case there is a problem, the user will be redirected, if everything is right, I start my "task schedule", and this will happen only the first access of the application. From there, you can do your inserts and the like in postconstruct.