实际需求:在项目启动时需要初始化一些数据库数据(非import.sql),或执行其他数据库操作(要执行import.sql需设置<property name="hibernate.hbm2ddl.auto" value="create-drop"/>或create)
[b]思路1:Seam提供了@Startup注解,可以指定某个Application Scope(或Session Scope)的组件在初始化时立即启动:[/b]
@Name("intiDate")
@Scope(ScopeType.APPLICATION)
public class InitDate {
public InitDate(){
}
@Create
public void init(){
// Do your initialization here
...
}
}
上述方法中的问题:数据库事务不提交,手动控制事务,报错:(未解决)
java.lang.IllegalStateException: JTA EntityManager cannot access a transactions
(类似问题的贴子http://forum.hibernate.org/viewtopic.php?p=2339865&sid=d981bb47fc5e1c82fdd735b4cb863e76)
[b]思路2:Seam定义了许多内置事件,应用程序可以用它们来进行特殊类型的框架集成,其中
org.jboss.seam.postInitialization — 当Seam被初始化并启动所有组件时被调用:[/b]
@Name("observeInitialization")
public class ObserveInitialization {
@In EntityManager entityManager;
@Observer("org.jboss.seam.postInitialization")
public void observe() {
// Do your initialization here
entityManager.persist(xxx);
}
}
[b]问题:同思路1,事务不提交
解决方法:用EJB[/b]
@Stateless
@Name("intiDate")
public class InitDate implements InitDateLocal{
@In
private EntityManager entityManager;
public InitDate(){
}
@Observer("org.jboss.seam.postInitialization")
public void init(){
Role role = new Role();
role.setId(1l);
role.setName("Test");
role.setDescription("Test");
entityManager.persist(role);
}
}
@Local
public interface InitDateLocal {
public void init();
}
[b]思路1:Seam提供了@Startup注解,可以指定某个Application Scope(或Session Scope)的组件在初始化时立即启动:[/b]
@Name("intiDate")
@Scope(ScopeType.APPLICATION)
public class InitDate {
public InitDate(){
}
@Create
public void init(){
// Do your initialization here
...
}
}
上述方法中的问题:数据库事务不提交,手动控制事务,报错:(未解决)
java.lang.IllegalStateException: JTA EntityManager cannot access a transactions
(类似问题的贴子http://forum.hibernate.org/viewtopic.php?p=2339865&sid=d981bb47fc5e1c82fdd735b4cb863e76)
[b]思路2:Seam定义了许多内置事件,应用程序可以用它们来进行特殊类型的框架集成,其中
org.jboss.seam.postInitialization — 当Seam被初始化并启动所有组件时被调用:[/b]
@Name("observeInitialization")
public class ObserveInitialization {
@In EntityManager entityManager;
@Observer("org.jboss.seam.postInitialization")
public void observe() {
// Do your initialization here
entityManager.persist(xxx);
}
}
[b]问题:同思路1,事务不提交
解决方法:用EJB[/b]
@Stateless
@Name("intiDate")
public class InitDate implements InitDateLocal{
@In
private EntityManager entityManager;
public InitDate(){
}
@Observer("org.jboss.seam.postInitialization")
public void init(){
Role role = new Role();
role.setId(1l);
role.setName("Test");
role.setDescription("Test");
entityManager.persist(role);
}
}
@Local
public interface InitDateLocal {
public void init();
}