我有类 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);
}
...
}
道实现:
@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>