2

我在我的项目中遇到了一个问题: entityManager.flush() 没有做任何事情,并且在退出 EJB 时,仅在提交之前完成刷新。

我的项目在 WebSphere 7 上运行。我通过 OpenJPA 使用 JPA2。我正在使用 Spring 进行自动装配。我正在使用容器管理事务。

下面的相关代码片段

持久性.xml

<persistence-unit name="persistenceUnit" transaction-type="JTA">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
    <properties>
        <property name="openjpa.TransactionMode" value="managed" />
        <property name="openjpa.ConnectionFactoryMode" value="managed" />
        <property name="openjpa.DynamicEnhancementAgent" value="true" />
    <property name="openjpa.jdbc.DBDictionary" value="StoreCharsAsNumbers=false" />
        <property name="openjpa.Log" value="SQL=TRACE"/>
    </properties>
</persistence-unit>

应用程序上下文.xml

<!-- Configure a JPA vendor adapter -->
<bean id="openJpaVendorAdapter" class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter">
    <property name="showSql" value="true" />
    <property name="generateDdl" value="false" />
</bean>

<!-- Entity Manager -->
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="jdbc/myappDS"/>
</bean>
<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory">
    <property name="persistenceUnitName" value="persistenceUnit"/>
    <property name="dataSource" ref="dataSource"/>
    <property name="jpaVendorAdapter" ref="openJpaVendorAdapter" />
</bean>

EJB3 豆

@Stateless(name="JPABaseEntityServiceBean")
@Configurable
public class JPABaseEntityServiceBean implements JPABaseEntityService {

    Logger logger = LoggerFactory.getLogger(JPABaseEntityServiceBean.class);

    @Autowired
    JPABaseEntityDao jpaBaseEntityDao;

    public JPABaseEntity persist(JPABaseEntity jpaBaseEntity) {
        return jpaBaseEntityDao.persist(jpaBaseEntity);
    }

道:

@Repository
public class JPABaseEntityDao implements BaseEntityDao {

    @PersistenceContext
    transient EntityManager entityManager;

    public JPABaseEntity persist(JPABaseEntity jpaBaseEntity) {
        Date now = new Date();
        jpaBaseEntity.setCreatedBy(TO_DO_ME);
        jpaBaseEntity.setUpdatedBy(TO_DO_ME);
        jpaBaseEntity.setUpdatedOn(now);
        jpaBaseEntity.setCreatedOn(now);

        entityManager.persist(jpaBaseEntity);

        entityManager.flush();

        return jpaBaseEntity;
    }

仅在离开 EJB 时才执行“插入”,这意味着 DAO 内的 entityManager.flush() 不起作用

4

1 回答 1

1

好的,以某种方式解决

似乎问题是实体管理器没有从 WebSphere 获取事务(可能是因为实体管理器是由 Spring 注入的,我没有深入调查)

所以我所做的是让 Spring 控制 EntityManager 中的事务:

1. added <tx:annotation-driven/> and <tx:jta-transaction-manager/> to applicationContext.xml
2. annotated the DAO methods with @Transactional

整个事务仍然由 EJB 处理,这意味着它仍然使用 WebSphere 的 CMT 和 JTA

由于依赖地狱,我遇到了很多问题(让我印象最深的是 hibernate-core,包括 JBoss 的 javax.transaction 实现,grr),但除此之外,一切似乎都很顺利

于 2013-06-27T03:41:39.013 回答