hibernate4.3通过嵌入id的多个列表级联合并

gmol1639  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(290)

休眠4.3.11
在hibernate中保存以下对象图时遇到问题。正在使用merge()方法保存雇主。

Employer 
   |_ List<EmployerProducts> employerProductsList; 
         |_ List<EmployerProductsPlan> employerProductsPlan;

雇主和雇员产品有一个自动生成的pk。employerproductsplan是一个复合键,由employerproducts id和带有计划代码的字符串组成。
当employerproducts列表中有一个临时对象级联到 List<EmployerProductsPlan> . 我一直试图克服的第一个错误是一个内部休眠npe。这里的这篇文章完美地描述了我遇到的一个问题,当使用@embeddeble和cascade持久化三个级别时,导致空指针在插入的id上休眠空指针
op留下了一条注解,指定了他们要解决的问题,但是当我更改为建议的Map时,我最终会遇到一个不同的错误。更改Map后,我现在得到

org.hibernate.NonUniqueObjectException: A different object with the same identifier value was already associated with the session : [com.webexchange.model.EmployerProductsPlan#com.webexchange.model.EmployerProductsPlanId@c733f9bd]

由于其他库依赖关系,我现在无法升级到4.3.x以上。这个项目使用的是springbootstarter数据jpa1.3.3。除了调用merge()并传递employer对象之外,没有其他工作在会话上执行。
下面是每个类的Map:
雇主

@Entity
@Table(name = "employer")
@lombok.Getter
@lombok.Setter
@lombok.EqualsAndHashCode(of = {"employerNo"})
public class Employer implements java.io.Serializable {

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "EMPLOYER_NO", unique = true, nullable = false)
    private Long employerNo;

     .....

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "employer", orphanRemoval = true)
    private List<EmployerProducts> employerProductsList = new ArrayList<>(0);
}

员工产品

@Entity
@Table(name = "employer_products")
@Accessors(chain = true) // has to come before @Getter and @Setter
@lombok.Getter
@lombok.Setter
@lombok.EqualsAndHashCode(of = {"employerProductsNo"})

public class EmployerProducts implements Serializable {

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "employer_products_no", unique = true, nullable = false)
    private Long employerProductsNo;

    @ManyToOne
    @JoinColumn(name = "employer_no", nullable = false)
    private Employer employer;

    ......

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "employerProducts", orphanRemoval = true)
    private List<EmployerProductsPlan> employerProductsPlanList = new ArrayList<>(0);
}

员工产品计划

@Accessors(chain = true) // has to come before @Getter and @Setter
@lombok.Getter
@lombok.Setter
@lombok.EqualsAndHashCode(of = {"id"})
@Entity
@Table(name="employer_products_plan")
public class EmployerProductsPlan implements Serializable {

    @EmbeddedId
    @AttributeOverrides({ @AttributeOverride(name = "plan", column = @Column(name = "epp_plan", nullable = false)),
            @AttributeOverride(name = "employerProductsNo", column = @Column(name = "employer_products_no", nullable = false)) })
    private EmployerProductsPlanId id;

    @ManyToOne
    @JoinColumn(name = "employer_products_no")
    @MapsId("employerProductsNo")
    private EmployerProducts employerProducts;

}

我正在用正在保存的employerproducts对象的相同示例填充上面的employerproducts。它是暂时的,没有填充id,因为它还不存在于db中。
员工产品计划ID

@Accessors(chain = true) // has to come before @Getter and @Setter
@lombok.Getter
@lombok.Setter
@lombok.EqualsAndHashCode(of = {"plan", "employerProductsNo"})
@Embeddable
public class EmployerProductsPlanId implements Serializable {

    private String plan;

    private Long employerProductsNo;

   // This was my previous mapping that was causing the internal NPE in hibernate
   /* @ManyToOne
    @JoinColumn(name = "employer_products_no")
    private EmployerProducts employerProducts;*/
}

更新:显示struts控制器和dao。在保存之前,从不从db加载employer对象。struts正在从http请求参数创建整个对象图。
struts 2.5控制器

@lombok.Getter
@lombok.Setter
public class EditEmployers extends ActionHelper implements Preparable {

    @Autowired
    @lombok.Getter(AccessLevel.NONE)
    @lombok.Setter(AccessLevel.NONE)
    private IEmployerDao employerDao;

    private Employer entity;

    ....

    public String save() {

        beforeSave();

        boolean newRecord = getEntity().getEmployerNo() == null || getEntity().getEmployerNo() == 0;
        Employer savedEmployer = newRecord ?
                employerDao.create(getEntity()) :
                employerDao.update(getEntity());

        setEntity(savedEmployer);

        return "success";
    }

    private void beforeSave() {
        Employer emp = getEntity();

        // associate this employer record with any products attached
        for (EmployerProducts employerProduct : emp.getEmployerProductsList()) {
            employerProduct.setEmployer(emp);

            employerProduct.getEmployerProductsPlanList().forEach(x ->
                    x.setEmployerProducts(employerProduct));
        }

        // check to see if branding needs to be NULL.  It will create the object from the select parameter with no id
        //  if a branding record has not been selected
        if (emp.getBranding() != null && emp.getBranding().getBrandingNo() == null) {
            emp.setBranding(null);
        }
    }

}

雇主dao

@Repository
@Transactional
@Service
@Log4j
public class EmployerDao  extends WebexchangeBaseDao implements IEmployerDao  {

    private Criteria criteria() {
        return getCurrentSession().createCriteria(Employer.class);
    }

    @Override
    @Transactional(readOnly = true)
    public Employer read(Serializable id) {
        return (Employer)getCurrentSession().load(Employer.class, id);
    }

    @Override
    public Employer create(Employer employer) {
        getCurrentSession().persist(employer);

        return employer;
    }

    @Override
    public Employer update(Employer employer) {

        getCurrentSession().merge(employer);

        return employer;
    }

}
8ljdwjyq

8ljdwjyq1#

目前为止,我的解决方案是循环浏览EmployeerProducts并检查新记录。在对父雇主调用merge()之前,我对新雇主调用了persist。我还将关联所有键的逻辑移到dao中,而不是在struts操作中。下面是我在雇主dao中的update()方法现在的样子

public Employer update(Employer employer) {

    // associate this employer record with any products attached
    for (EmployerProducts employerProduct : employer.getEmployerProductsList()) {
        employerProduct.setEmployer(employer);

        if (employerProduct.getEmployerProductsNo() == null) {
            // The cascade down to employerProductsPlanList has issues getting the employerProductsNo
            // automatically if the employerProduct does not exists yet.  Persist the new employer product
            // before we try to insert the new composite key in the plan
            // https://stackoverflow.com/questions/54517061/hibernate-4-3-cascade-merge-through-multiple-lists-with-embeded-id
            List<EmployerProductsPlan> plansToBeSaved = employerProduct.getEmployerProductsPlanList();
            employerProduct.setEmployerProductsPlanList(new ArrayList<>());
            getCurrentSession().persist(employerProduct);

            // add the plans back in
            employerProduct.setEmployerProductsPlanList(plansToBeSaved);
        }

        // associate the plan with the employer product
        employerProduct.getEmployerProductsPlanList().forEach(x ->
                    x.getId().setEmployerProductsNo(employerProduct.getEmployerProductsNo())
        );

    }

    return (Employer)getCurrentSession().merge(employer);
}

相关问题