用Spring

时间:2017-01-19 00:08:13

标签: java spring hibernate unit-testing jpa

我创建了简单的JPA实体:主题和Word。主题包含单词列表。

@ManyToMany(fetch = FetchType.EAGER, cascade = {CascadeType.MERGE, CascadeType.REMOVE})
@JoinTable
private List<Word> words;

现在我想使用内存H2数据库来测试我的DAO。在测试类中,我编写了不同的测试来操作数据。但是我想为每个测试获得一个干净的数据库,所以我添加了tearDown方法来删除所有单词和主题。

我的测试类的片段:

@RunWith(SpringRunner.class)
@SpringBootTest
public class TopicServiceJpaDaoTest {
    @Autowired
    private TopicDao topicDao;

    @Autowired
    private WordDao wordDao;

    // different test methods

    @After
    public void tearDown() throws Exception {
        topicDao.deleteAll();
        wordDao.deleteAll();
    }
}
  1. 但是当我尝试在类中运行所有测试时,我收到一个错误,该条目被锁定。
  2. 此外,当我运行所有集成测试时,收到以下错误:Unable to acquire JDBC Connection
  3. 条目的堆栈跟踪已锁定错误:

    javax.persistence.PessimisticLockException: could not execute statement
    
        at org.hibernate.jpa.spi.AbstractEntityManagerImpl.wrapLockException(AbstractEntityManagerImpl.java:1760)
        at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1649)
        at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1602)
        at org.hibernate.jpa.spi.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:1700)
        at org.hibernate.jpa.spi.AbstractQueryImpl.executeUpdate(AbstractQueryImpl.java:70)
        at io.github.solomkinmv.glossary.persistence.dao.impl.WordServiceJpaDao.deleteAll(WordServiceJpaDao.java:66)
        at io.github.solomkinmv.glossary.persistence.dao.impl.TopicServiceJpaDaoTest.tearDown(TopicServiceJpaDaoTest.java:287)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
        at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
        at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
        at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:33)
        at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
        at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
        at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
        at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
        at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
        at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
        at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
        at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
        at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
        at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
    Caused by: org.hibernate.PessimisticLockException: could not execute statement
        at org.hibernate.dialect.H2Dialect$3.convert(H2Dialect.java:370)
        at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
        at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109)
        at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:95)
        at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:207)
        at org.hibernate.hql.internal.ast.exec.BasicExecutor.doExecute(BasicExecutor.java:91)
        at org.hibernate.hql.internal.ast.exec.BasicExecutor.execute(BasicExecutor.java:60)
        at org.hibernate.hql.internal.ast.exec.DeleteExecutor.execute(DeleteExecutor.java:111)
        at org.hibernate.hql.internal.ast.QueryTranslatorImpl.executeUpdate(QueryTranslatorImpl.java:429)
        at org.hibernate.engine.query.spi.HQLQueryPlan.performExecuteUpdate(HQLQueryPlan.java:374)
        at org.hibernate.internal.SessionImpl.executeUpdate(SessionImpl.java:1348)
        at org.hibernate.internal.QueryImpl.executeUpdate(QueryImpl.java:102)
        at org.hibernate.jpa.internal.QueryImpl.internalExecuteUpdate(QueryImpl.java:405)
        at org.hibernate.jpa.spi.AbstractQueryImpl.executeUpdate(AbstractQueryImpl.java:61)
        ... 34 more
    Caused by: org.h2.jdbc.JdbcSQLException: Timeout trying to lock table ; SQL statement:
    delete from word [50200-193]
        at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
        at org.h2.message.DbException.get(DbException.java:168)
        at org.h2.command.Command.filterConcurrentUpdate(Command.java:307)
        at org.h2.command.Command.executeUpdate(Command.java:260)
        at org.h2.jdbc.JdbcPreparedStatement.executeUpdateInternal(JdbcPreparedStatement.java:160)
        at org.h2.jdbc.JdbcPreparedStatement.executeUpdate(JdbcPreparedStatement.java:146)
        at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:204)
        ... 43 more
    Caused by: org.h2.jdbc.JdbcSQLException: Concurrent update in table "WORD": another transaction has updated or deleted the same row [90131-193]
        at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
        at org.h2.message.DbException.get(DbException.java:168)
        at org.h2.mvstore.db.MVTable.convertException(MVTable.java:898)
        at org.h2.mvstore.db.MVPrimaryIndex.remove(MVPrimaryIndex.java:168)
        at org.h2.mvstore.db.MVTable.removeRow(MVTable.java:677)
        at org.h2.command.dml.Delete.update(Delete.java:95)
        at org.h2.command.CommandContainer.update(CommandContainer.java:98)
        at org.h2.command.Command.executeUpdate(Command.java:258)
        ... 46 more
    Caused by: java.lang.IllegalStateException: Entry is locked [1.4.193/101]
        at org.h2.mvstore.DataUtils.newIllegalStateException(DataUtils.java:765)
        at org.h2.mvstore.db.TransactionStore$TransactionMap.set(TransactionStore.java:1031)
        at org.h2.mvstore.db.TransactionStore$TransactionMap.remove(TransactionStore.java:989)
        at org.h2.mvstore.db.MVPrimaryIndex.remove(MVPrimaryIndex.java:162)
        ... 50 more
    

    我尝试过对数据库网址进行不同的操作,例如添加MVCC=TRUE,但没有任何变化。

    看起来我的单元测试方法是错误的。热门以正确的方式做到这一点?

    我不使用Spring Data,只需简单的JPA实现。我的DAO实施:

    @Repository
    public class TopicServiceJpaDao extends AbstractJpaDaoService implements TopicDao {
        private static final Logger LOGGER = LoggerFactory.getLogger(TopicServiceJpaDao.class);
    
        @Override
        public List<Topic> listAll() {
            EntityManager entityManager = emf.createEntityManager();
    
            return entityManager.createQuery("FROM Topic", Topic.class)
                                .getResultList();
        }
    
        @Override
        public Optional<Topic> getById(Long id) {
            EntityManager entityManager = emf.createEntityManager();
    
            return Optional.ofNullable(entityManager.find(Topic.class, id));
        }
    
        @Override
        public Topic saveOrUpdate(Topic unsavedTopic) {
            EntityManager entityManager = emf.createEntityManager();
    
            entityManager.getTransaction().begin();
            Topic savedTopic = entityManager.merge(unsavedTopic);
            entityManager.getTransaction().commit();
            return savedTopic;
        }
    
        @Override
        public void delete(Long id) {
            EntityManager entityManager = emf.createEntityManager();
    
            entityManager.getTransaction().begin();
            Topic entity = entityManager.find(Topic.class, id);
            if (entity == null) {
                LOGGER.error("No such entity in the DB");
                throw new EntityNotFoundException("Topic id: " + id);
            }
            entityManager.remove(entityManager.find(Topic.class, id));
            entityManager.getTransaction().commit();
        }
    
        @Override
        public void deleteAll() {
            EntityManager entityManager = emf.createEntityManager();
    
            entityManager.getTransaction().begin();
            entityManager.createQuery("DELETE FROM Topic").executeUpdate();
            entityManager.getTransaction().commit();
        }
    }
    

2 个答案:

答案 0 :(得分:4)

如果使用Spring Data JPA Repository

,这个答案就足够了

使用Spring Data JPA存储库,Dao可以替换为:

public interface TopicRepository extends JpaRepository<Topic, Long> {
    // no need for code here   
}

从我在Dao中看到的,它几乎是一个完美的匹配:

  • listAll - &gt;的findAll
  • getById - &gt; findOne
  • saveOrUpdate - &gt;保存
  • 删除
  • deleteAll。

这不是你的问题,但你可以看看Spring Data JPA Repository

您可以使用@DataJpaTest代替,这将负责加载内存中的h2数据库和回滚。

来源:https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html

  

默认情况下,它将配置内存中的嵌入式数据库,扫描   @Entity类并配置Spring Data JPA存储库。定期   @Component bean不会加载到ApplicationContext中。

     

数据JPA测试在每次测试结束时都是事务性和回滚   默认[...]

     

Data JPA测试也可能会注入一个提供的TestEntityManager bean   标准JPA EntityManager的替代品,专门设计   用于测试。如果你想在外面使用TestEntityManager   @DataJpaTests您还可以使用@AutoConfigureTestEntityManager   注解。 [...]

@RunWith(SpringRunner.class)
@DataJpaTest
public class ExampleRepositoryTests {

    @Autowired
    private TestEntityManager entityManager;

    @Autowired
    private UserRepository repository;

    @Test
    public void testExample() throws Exception {
        this.entityManager.persist(new User("sboot", "1234"));
        User user = this.repository.findByUsername("sboot");
        assertThat(user.getUsername()).isEqualTo("sboot");
        assertThat(user.getVin()).isEqualTo("1234");
    }
}

答案 1 :(得分:0)

我提供的另一个答案是Spring Data JPA Repository,你没有使用它。

再次查看您的错误和代码,这是我的想法:

  

JdbcSQLException:表“WORD”中的并发更新:另一个   交易已更新或删除同一行[90131-193]

表示交易未正确关闭。

我相信您的Dao包含一个错误:如果出现错误,您不会回滚。

例如,在您的setenv PYTHONPATH $HOME/.locak/lib/python2.7 setenv LD_LIBRARY_PATH $HOME/.local/lib 方法中:

saveOrUpdate

如果public Topic saveOrUpdate(Topic unsavedTopic) { EntityManager entityManager = emf.createEntityManager(); entityManager.getTransaction().begin(); Topic savedTopic = entityManager.merge(unsavedTopic); entityManager.getTransaction().commit(); return savedTopic; } 失败,将启动一个事务,但永远不会被提交或回滚。

您可以将其更改为:

entityManager.merge(unsavedTopic);

同样适用于public Topic saveOrUpdate(Topic unsavedTopic) { EntityManager entityManager = emf.createEntityManager(); try{ entityManager.getTransaction().begin(); Topic savedTopic = entityManager.merge(unsavedTopic); entityManager.getTransaction().commit(); } catch(RuntimeException e){ entityManager.getTransaction().rollback(); throw e; //you choose how to handle the exceptions. } return savedTopic; } delete