0

Similar to Bootstrap.groovy in Grails, how to add some initial data when an app starts?

Since in @PostContstruct method, the EntityManager is not available in Stateless session beans (or am I doing something wrong?), so what should be the right way to insert some initial data?

E.g. I want to add one Admin account in my system when the application starts.

1 Answers1

4

Since in @PostContstruct method, the EntityManager is not available

This is not true, @PostConstruct is usually the right place where to retrieve initial data for a view from the db.

When application starts you can use a Singleton EJB for startup operations, like adding an admin account, and annotate the EJB with @Startup:

@Startup
@Singleton
public class MySingleton implements Serializable {
    @PersistenceContext
    private EntityManager em;

    @PostConstruct
    public void init() {
        // here you can perform queries or transactions
    }
}

Enterprise Java Beans, like Singleton, are transactional by default. With Java EE 7, CDI beans become transactional if they are annotated with @Transactional.

Links:

perissf
  • 15,979
  • 14
  • 80
  • 117
  • First of all, thank for your reply! I was using Stateless SessionBeans and always getting the EntityManager null in PostConstruct, any idea about that? (updated the question) – Shaikh Sonny Aman Jul 14 '14 at 09:13
  • It can be null if you instantiate the EJB yourself. Instead, you should used EJBs in other container-managed beans like CDI beans and inject it using `@EJB` annotation. – perissf Jul 14 '14 at 09:21
  • Not really. I created a basic app with one EJB module and one war module. And i exposed my SessionBeans method via ReST path annotation - just 'hello world'- which works. Then I configured database and added an EM in my SessionBean as: @Resource private EntityManager entityManager; but actually it is always null ... – Shaikh Sonny Aman Jul 14 '14 at 10:07
  • Can you try with `@PersistenceContext` instead of `@Resource`? And post the Session Bean code. – perissf Jul 14 '14 at 10:14
  • Used, but I just found there is not JDBC resource created in Glassfish and I need to configure it. Thought it would be automatically created once I configured the datasource while creating the entity using Netbeans. I need to RTFM even more, comparing to Grails.. its a bit more :p Thanks. – Shaikh Sonny Aman Jul 14 '14 at 10:35