gpt4 book ai didi

java - 在测试和 Controller 中标记为事务的方法的不同行为

转载 作者:行者123 更新时间:2023-12-01 14:04:56 25 4
gpt4 key购买 nike

我将 CandidateService 类标记为 @Transactional

@Transactional
@Service("candidateService")
public class CandidateService {

@Autowired
private CandidateDao candidateDao;

....

public void add(Candidate candidate) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String login = auth.getName();
User user = utilService.getOrSaveUser(login);
candidate.setAuthor(user);
candidateDao.add(candidate);
}
...
}

dao 实现:

@Override
public Integer add(Candidate candidate) throws HibernateException{
Session session = sessionFactory.getCurrentSession();
if (candidate == null) {
return null;
}
Integer id = (Integer) session.save(candidate);
return id;

}

如果我在@controller类中编写:

@RequestMapping("/submitFormAdd")
public ModelAndView submitFormAdd(
Model model,
@ModelAttribute("myCandidate") @Valid Candidate myCandidate,
BindingResult result,
RedirectAttributes redirectAttributes) {
if (result.hasErrors()) {
return new ModelAndView("candidateDetailsAdd");
}

myCandidate.setDate(new Date());
candidateService.add(myCandidate);

.....
}

执行此方法后,数据放入数据库!

如果我写测试:

@ContextConfiguration(locations = {"classpath:/test/BeanConfig.xml"})
public class CandidateServiceTest extends AbstractTransactionalJUnit4SpringContextTests{

@Autowired
CandidateService candidateService;

@BeforeClass
public static void initialize() throws Exception{

UtilMethods.createTestDb();

}
@Before
public void setup() {
TestingAuthenticationToken testToken = new TestingAuthenticationToken("testUser", "");
SecurityContextHolder.getContext().setAuthentication(testToken);
}

@After
public void cleanUp() {
SecurityContextHolder.clearContext();
}
@Test
public void add(){
Candidate candidate = new Candidate();
candidate.setName("testUser");
candidate.setPhone("88888");
candidateService.add(candidate);
List<Candidate> candidates = candidateService.findByName(candidate.getName());
Assert.assertNotNull(candidates);
Assert.assertEquals("88888", candidates.get(0).getPhone());
}
}

测试是绿色的,但执行后我在数据库中看不到数据。

您能解释一下原因以及如何解决吗?

更新

configuration:
<tx:annotation-driven transaction-manager="transactionManager" />

<!-- Менеджер транзакций -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>

最佳答案

@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)

上面的测试类不会影响数据库。

设置或添加defaultRollback = false以查看表中保留的数据。

关于java - 在测试和 Controller 中标记为事务的方法的不同行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18977796/

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