我有这个型号:
@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;
}
我的行为很奇怪。如果我给候选人增加新的空缺 - 它运作良好。但如果我删除空缺 - 它不起作用。
我不理解。
答案 0 :(得分:1)
当你从候选人名单中删除空缺时,不要忘记从候选人名单中删除候选人,反之亦然。还要记住:如果你的系统中某处有某个地方,以后发送已经删除的空缺(反之亦然),该实体将再次被保留。