gpt4 book ai didi

java - 使用 Spring 正确测试 JPA DAO

转载 作者:行者123 更新时间:2023-12-01 18:00:03 27 4
gpt4 key购买 nike

我创建了简单的 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. 此外,当我运行所有集成测试时,我收到以下错误:无法获取 JDBC 连接

条目的堆栈跟踪已锁定错误:

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

我尝试了对数据库 URL 进行不同的操作,例如添加 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();
}
}

最佳答案

只有使用 Spring Data JPA Repository,这个答案才足够

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

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

从我在道中看到的来看,它几乎是完美的匹配:

  • listAll -> findAll
  • getById -> findOne
  • saveOrUpdate -> 保存
  • 删除
  • 全部删除。

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

<小时/>

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

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

By default it will configure an in-memory embedded database, scan for @Entity classes and configure Spring Data JPA repositories. Regular @Component beans will not be loaded into the ApplicationContext.

Data JPA tests are transactional and rollback at the end of each test by default [...]

Data JPA tests may also inject a TestEntityManager bean which provides an alternative to the standard JPA EntityManager specifically designed for tests. If you want to use TestEntityManager outside of @DataJpaTests you can also use the @AutoConfigureTestEntityManager annotation. [...]

@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");
}
}

关于java - 使用 Spring 正确测试 JPA DAO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41731644/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com