EJB3: Right way to insert initial data when application starts like Grails Bootstrap?

本秂侑毒 提交于 2019-12-12 01:59:43

问题


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:


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:

  • The Java EE 7 Tutorial by Oracle: Container-Managed Transactions
  • The Java EE 7 Tutorial by Oracle: Using the @PostConstruct and @PreDestroy Annotations with CDI Managed Bean Classes


来源:https://stackoverflow.com/questions/24725062/ejb3-right-way-to-insert-initial-data-when-application-starts-like-grails-boots

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!