@Transactional としてマークされたクラス CandidateService があります
@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>