Reputation:
I have this code:
Candidate candidate = new Candidate();
candidate.setName("testUser");
candidate.setPhone("88888");
candidateService.add(candidate);
sessionFactory.getCurrentSession().flush();
return candidate;
CandidateService marked as @Transactional
;
Can you explain me why after execution of candidateService.add(candidate);
candidate get id field value.
Maybe it is normally?
candidateService.add(candidate) realization:
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;
}
I thought it happened if candidate in persistent state.
I messed.
Upvotes: 0
Views: 769
Reputation: 121998
Since the ID is primary key of the table candiate,when you add it to database a Id generates and returned by the save method.
If you see docs of save method.
Persist the given transient instance, first assigning a generated identifier. (Or using the current value of the identifier property if the assigned generator is used.) This operation cascades to associated instances if the association is mapped with cascade="save-update".
Returns: the generated identifier
Upvotes: 1