【发布时间】:2021-07-23 19:41:57
【问题描述】:
我目前正在尝试我的函数是否适用于我当前的数据库,但我不断得到一个空对象。我的测试如下:
@Test
public void findJobOfferByIdReturnsCorrectJobOffer() {
User user = UserBuilder.anUser().build();
JobOffer firstJobOffer = JobOfferBuilder.aJobOffer()
.withId(108L)
.withCompany(user)
.build();
JobOffer secondJoboffer = JobOfferBuilder.aJobOffer()
.withAmountPerSession(55)
.withCompany(user)
.withId(208L)
.withJobDescription("Software Tester in PHP")
.build();
userDao.saveUser(user);
jobOfferDao.saveJobOffer(firstJobOffer);
jobOfferDao.saveJobOffer(secondJoboffer);
entityManager.clear();
entityManager.flush();
Optional<JobOffer> retrievedJobOffer = jobOfferDao.findJobOfferById(firstJobOffer.getId());
assertTrue(retrievedJobOffer.isPresent());
JobOffer jobOffer = retrievedJobOffer.get();
assertEquals(jobOffer.getId(), firstJobOffer.getId());
assertNotEquals(jobOffer.getId(), secondJoboffer.getId());
}
测试使用以下 DAOImpl 存储库:
@Repository
public class JobOfferDaoImpl implements JobOfferDao {
@PersistenceContext
private EntityManager entityManager;
private static final Logger LOGGER = LogManager.getLogger(UserDaoImpl.class);
@Override
public Optional<JobOffer> findJobOfferById(Long id) {
TypedQuery<JobOffer> jobOfferQuery = entityManager.createNamedQuery("findJobOfferById", JobOffer.class);
jobOfferQuery.setParameter("jobOfferId", id);
try {
return Optional.of(jobOfferQuery.getSingleResult());
} catch (NoResultException e) {
return Optional.empty();
}
}
@Transactional
public void saveJobOffer(JobOffer jobOffer) {
if (findJobOfferById(jobOffer.getId()).isEmpty()) {
entityManager.merge(jobOffer);
LOGGER.info(String.format("Joboffer with id %d is inserted in the database", jobOffer.getId()));
} else {
throw new JobOfferNotFoundException();
}
}
}
为“findJobOfferById”选择正确jobOffer的查询如下:
@NamedQuery(name = "findJobOfferById", query = "SELECT j from JobOffer j WHERE j.id = :jobOfferId"),
尝试调试时,我得到以下信息:
【问题讨论】:
标签: spring-boot hibernate jpa junit spring-data-jpa