2
我有這樣的模式:多對多協會。 DATAS不會刪除
@Entity
@Table(name = "candidate")
@XmlRootElement(name = "candidate")
public class Candidate{
@ManyToMany(mappedBy = "candidates", fetch = FetchType.EAGER)
@XmlTransient
public Set<Vacancy> getVacancies() {
return vacancies;
}
....
}
和背部映射:
@Entity
@Table(name = "vacancy")
@XmlRootElement(name="vacancy")
public class Vacancy {@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "vacancy_candidate", joinColumns = @JoinColumn(name = "vacancy_id"), inverseJoinColumns = @JoinColumn(name = "candidate_id"))
public Set<Candidate> getCandidates() {
return candidates;
}
...
}
而且我有這麼控制器的方法:
@RequestMapping("/saveCandidate")
public String saveCandidate(
Model model,
@ModelAttribute("candidateFromRequest") Candidate candidateFromRequest,
@ModelAttribute("vacanciesForCandidate") Set<Vacancy> vacanciesForCandidate,
RedirectAttributes redirectAttributes) {
candidateService.updateCandidateAndLinkedEntities(candidateFromRequest,
vacanciesForCandidate,...);
...
}
一個新的水平:
@Transactional
@Service("candidateService")
public class CandidateService {
public void updateCandidateAndLinkedEntities(Candidate candidate,
Set<Vacancy> vacancies, ...) {
if (candidate == null)
throw new NullPointerException("null candidate entity");
if (vacancies != null) {
candidate.setVacancies(vacancies);
for (Vacancy vacancy : vacancies) {
vacancy.getCandidates().add(candidate);
vacancyDao.update(vacancy);
}
}
candidateDao.update(candidate);//here all right, how I wish(I am about state of candidate entity)
}
...
}
更新方法實現:
空缺:
@Override
public boolean update(Vacancy vacancy) throws HibernateException {
Session session = sessionFactory.getCurrentSession();
if (vacancy == null) {
return false;
}
session.update(vacancy);
return true;
}
候選人:
@Override
public boolean update(Candidate candidate) throws HibernateException{
Session session = sessionFactory.getCurrentSession();
if (candidate == null) {
return false;
}
session.update(candidate);
return true;
}
我有奇怪的行爲。如果我給候選人增加新的空缺 - 它的效果很好。但是,如果我刪除空缺 - 這是行不通的。
這是不明白我。