问题
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