JPA:外部容器事务未提交

时间:2015-12-25 13:24:21

标签: java maven jpa junit persistence

我正在为我的应用程序测试JPA。

与DB的连接似乎是成功的,

Running com.vgorcinschi.rimmanew.ejbs.OutsideContainerJpaTests 
[EL Info]: 2015-12-25 07:32:26.202--ServerSession(1302779492)--EclipseLink, version: Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd
[EL Info]: connection: 2015-12-25 07:32:26.493--ServerSession(1302779492)--file:/home/vgorcinschi/NetBeansProjects/RimmaNew/target/classes/_outsideContainer login successful

但数据不存在。

因为我的应用程序在GlassFish上运行,而我正在尝试容器外的JUnit测试,所以我创建了第二个持久性单元。这就是persistence.xml文件中的内容(注意我已将我的凭据屏蔽到数据库):

<persistence-unit name="outsideContainer" transaction-type="RESOURCE_LOCAL">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties>
        <property name="javax.persistence.schema-generation.database.action" value="create"/>
        <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
        <property name="javax.persistence.jdbc.url"
                  value="jdbc:mysql://127.0.0.1:3306/beaty_shop?zeroDateTimeBehavior=convertToNull"/>
        <property name="javax.persistence.jdbc.user" value="**********"/>
        <property name="javax.persistence.jdbc.password" value="*************"/>
    </properties>
</persistence-unit>

这是返回EntityManagerFactory的单例方法:

public static EntityManagerFactory getUniqueInstance() {
    if (uniqueInstance == null) {
        synchronized (EntityManagerFactoryProvider.class) {
            if (uniqueInstance == null) {
                uniqueInstance = Persistence.createEntityManagerFactory("outsideContainer");
            }
        }
    }
    return uniqueInstance;
}

这是Repository Stub,它不会抛出异常,但也不会将数据保存到DB。事务已启动并提交......

public class JpaAppointmentRepositoryStub implements AppointmentRepository {



  private EntityManagerFactory emf;

    public JpaAppointmentRepositoryStub(EntityManagerFactory emf) {
        this.emf = emf;
    }

    public JpaAppointmentRepositoryStub() {
    }

    @Override
    public void add(Appointment appointment) {
        EntityManager em = entityManagerFactory.createEntityManager();
        EntityTransaction trans = em.getTransaction();
        try {
            trans.begin();
            em.persist(appointment);
            trans.commit();
        } catch (Exception e) {
            trans.rollback();
        } finally {
            em.close();
        }
    }

    @Override
    public void update(Appointment appointment) {
        EntityManager em = entityManagerFactory.createEntityManager();
        em.merge(appointment);
    }

    @Override
    public Appointment get(long id) {
        EntityManager em = entityManagerFactory.createEntityManager();
        try {
            return em.find(Appointment.class, id);
        } catch (NoResultException e) {
            return null;
        } finally {
            em.close();
        }
    }


}

来自EntityManager的事务不为空:

@Test
public void aTransactionIsNotNull(){
    EntityManager em = entityManagerFactory.createEntityManager();
    EntityTransaction trans = em.getTransaction();
    assertNotNull(trans);
    em.close();
}

最后一个有趣且有用的信息是存储库正在运行&#34;由具有Repository的保存和更新操作的单一方法的Service类。所以唯一的缺点应该是在每次调用时打开和关闭两个实体管理器:

public class OutsideContainerAppointmentService implements AppointmentService{
private final AppointmentRepository repository;
...
@Override
    public void save(Appointment appointment) {
        if (findById(appointment.getId()) != null) 
            repository.update(appointment);
        else 
            repository.add(appointment);        
    }
...
}

MySQL Connector / J在此Maven项目的测试依赖项中(但由于登录成功,这不是问题)。

那么您认为可能是什么问题?

1 个答案:

答案 0 :(得分:1)

即使它没有意义(至少到目前为止),正确的解决方案就是这样。

我添加了.joinTransaction()方法,一切正常。

    @Override
    public void add(Appointment appointment) {
        EntityManager em = entityManagerFactory.createEntityManager();
        EntityTransaction trans = em.getTransaction();
        trans.begin();
        try {
                //this is the line that I have added                
                em.joinTransaction();
                em.persist(appointment);
                trans.commit();
            } catch (Exception e) {
                trans.rollback();
            } finally {
                em.close();
            }
        }

但根据JPA wiki我不应该在这种情况下使用.joinTransaction():

  

joinTransaction仅用于JTA托管的EntityManagers(JTA   persistence.xml中的transaction-type)。对于RESOURCE_LOCAL   EntityManagers你可以随时提交JPA事务   欲望。

另一个&#34; bug&#34;我必须解决的问题是将appointmentService.save(dummy);转移到setUp()方法之外,并转移到@Test注释方法中。这就是我开始双重写入数据库的原因。