EJB3:应用程序启动时插入初始数据的正确方法就像Grails Bootstrap? [英] EJB3: Right way to insert initial data when application starts like Grails Bootstrap?

查看:223
本文介绍了EJB3:应用程序启动时插入初始数据的正确方法就像Grails Bootstrap?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类似于Grails中的Bootstrap.groovy,在应用程序启动时如何添加一些初始数据?

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

由于在@PostContstruct方法中,EntityManager在Stateless中不可用会话bean(或者我做错了什么?),那么应该是正确的方法来插入一些初始数据?

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.

推荐答案


PostContype方法,EntityManager不可用

Since in @PostContstruct method, the EntityManager is not available

这不是真的, @PostConstruct 通常是从数据库检索视图的初始数据的正确位置。

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

当应用程序启动时,您可以使用Singleton EJB进行启动操作,例如添加管理员帐户,并使用 @Startup

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
    }
}

企业Java Bean,像Singleton,默认情况下是事务性的。使用Java EE 7,如果CDI bean注释为 @Transactional

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

链接

  • 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

这篇关于EJB3:应用程序启动时插入初始数据的正确方法就像Grails Bootstrap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆