当前位置: 首页 > 工具软件 > Ejb3Unit > 使用案例 >

jboss jta mysql_如何在JBoss AS 6,Hibernate 3.6,JPA,JTA和EJB3中使用...

梁烨
2023-12-01

我正在尝试使用CMT设置网络应用程序.我已经让它在Eclipse中独立运行了,现在我正在尝试使用Struts 1.0在Jboss AS 6中运行它.我选择了CMT,因为我读过的doco暗示它是最好的和“使用最不详细”.所以看起来像Hibernate 3.6的现代/良好实践使用.

我可以使用以下代码提取从MySQL数据库加载对象,但持久化对象不会被刷新/同步/保存到数据库:

从Struts 1.0 Action类中:

InitialContext ctx = new InitialContext();

EntityManagerFactory emf = (EntityManagerFactory)ctx.lookup("java:/MyEntityManagerFactory");

然后将’emf’传递给我的DAO类的方法,总结如下:

@PersistenceContext(unitName="purejetJPA") EntityManager em;

@TransactionAttribute(TransactionAttributeType.REQUIRED)

exampleMethodInMyCustomDAOClass() {

EntityManager em = emf.createEntityManager();

em.find(MyCustomEntity.class, 542); // works successfully

em.persist(newInstanceOfMyCustomEntity); // this executes ok and generates an ID

// however the entity is not saved to database upon completion

}

persistence.xml的内容:

org.hibernate.ejb.HibernatePersistence

java:/MySqlDS

my.custom.entity.Classes

Hibernate EntityManager文档对如何实现CMT的描述非常有限:

我们的CMT和EJB3容器使用的实体管理器/事务管理习惯用法简化为:

????//通过注射CMT成语

????@PersistenceContext(name =“sample”)EntityManager em;

使用EJB / CMT进行事务划分

我们的目标实际上是从数据访问代码中删除任何事务划分代码:

@TransactionAttribute(TransactionAttributeType.REQUIRED)

public void doSomeWork() {

// Do some work

factory.getCurrentSession().load(...);

factory.getCurrentSession().persist(...);

}

我的问题:

>在“actory.getCurrentSession().load(…);”行中,“factory”是什么类型,我该如何创建它?是Hibernate.SessionFactory吗?还是Jboss或HTTP会话?

>在行“@PersistenceContext(name =”sample“)EntityManager em;”什么是“名字”指的是什么?我在论坛上找到了一个使用“unitName”而不是“name”的例子.这行是如何我首先声明我用来调用.persist().find()等的EntityManager对象? (因此我的代码不需要创建EntityManagerFactory)

>我应该考虑研究和使用“Java上下文和依赖注入”(CDI)吗?

任何帮助非常感谢.请让我知道我应该提供的其他代码或配置文件

更新:

如果我不使用EntityManagerFactory,并使用@PersistenceContext检索EntityManager,那么像我的“会话bean”这个代码(基于每个用户会话的类恢复保存实体)应该是这样做的方式?

@Stateful

@TransactionManagement(value=TransactionManagementType.BEAN)

public class X implements IX {

@PersistenceContext(unitName="MySQL", type=PersistenceContextType.EXTENDED)

private EntityManager em;

@Resource

private UserTransaction tx;

public void doStuff() {

tx.begin();

em.joinTransaction();

em.find(myEntity);

em.perrsist(myEntity);

tx.commit();

}

如果这是正确的轨道,persistence.xml需要什么?从我对doco和网络的所有阅读中,我不确定可能需要哪些内容:

 类似资料: