有以下关系 公司和公司行业是多对多的关系,映射成两个一对多,
当我保存完公司信息时,且同时保存公司行业。
当我修改时行业修改不了!每次都会增加!
代码如下,我在查出公司时如果删除的话,中间表时出错!请解决! /**客户修改公司信息*/
public String customerUpdateCompany(){
Company cCompany =companyService.findCompanyById(company.getCompanyId());
String[] industrys = request.getParameterValues("industry");// 获取选中行业
Set<CompanyIndustryRef> companyIndustryRefs = new LinkedHashSet<CompanyIndustryRef>();//真实行业
int length=industrys==null?0:industrys.length;
System.out.println(length);
for(int i=0;i<length;i++){
  int temp =Integer.valueOf(industrys[i]);
  Industry tempIndustry = industryService.findIndustryById(temp);
  CompanyIndustryRef cr =new CompanyIndustryRef();
  cr.setCompany(cCompany);
  cr.setIndustry(tempIndustry);
  companyIndustryRefs.add(cr);
}
Set<CompanyIndustryRef>   industryRefs  = cCompany.getCompanyIndustryRefs();
Iterator<CompanyIndustryRef>  companyIndustryRef = industryRefs.iterator();
while(companyIndustryRef.hasNext()){
companyIndustryRefService.deleteCompanyIndustryRef(companyIndustryRef.next());
}
 cCompany.setCompanyIndustryRefs(companyIndustryRefs);//公司行业中间表如果不做删除操作:
Set<CompanyIndustryRef>   industryRefs  = cCompany.getCompanyIndustryRefs();
Iterator<CompanyIndustryRef>  companyIndustryRef = industryRefs.iterator();
while(companyIndustryRef.hasNext()){
companyIndustryRefService.deleteCompanyIndustryRef(companyIndustryRef.next());
}每次修改完后都会新增一条记录,
如果做删除操作出现异常。 org.hibernate.ObjectDeletedException:

解决方案 »

  1.   

    多对多关系,中间应该有个关系表。比如表A和表B是多对多关系,那么需要一个关系表C把这个多对多关系管理起来。如果楼主想把A表和B表的多对多关系拆分成A表与关系表C和B表与关系表C两个关联映射的话。应该是两个“1对1”关系  而不是 两个“一对多”关系。楼主改改关联映射试一试。
      

  2.   

    设置了!问题解决了!现在的做法是从一端批量删除,删除有公司存在的中间表信息记录!!/**删除公司行业中间映射记录 */
    public void deleteCompanyIndustryRef(int companyId){
    String hql="delete   CompanyIndustryRef  as cir where cir.company.companyId=?";
            this.companyIndustryRefDao.getSessionFactory().getCurrentSession().createQuery(hql).setParameter(0, companyId).executeUpdate();
    }一定要记得加.executeUpdate();否则执行hql 语句并不会发送sql!