Hibernate 4.3级联合并具有嵌入ID的多个列表

时间:2019-02-04 13:22:01

标签: java hibernate jpa hibernate-mapping

休眠4.3.11

我在将以下对象图保存到休眠状态时遇到问题。正在使用merge()方法保存雇主。

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

Employer&EmployerProducts具有自动生成的pk。 EmployerProductsPlan是一个复合键,由EmployerProducts id和带有计划代码的字符串组成。

当EmployerProducts列表中存在一个级联到List<EmployerProductsPlan>的临时对象时,将发生错误。我一直试图克服的第一个错误是内部休眠NPE。这里的帖子完美地描述了我遇到的导致空指针Hibernate NullPointer on INSERTED id when persisting three levels using @Embeddable and cascade

的问题

OP留下了评论,指出了他们要解决的问题,但是当更改为建议的映射时,我最终遇到了另一个错误。更改映射后,我现在得到

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以上。该项目使用的是spring-boot-starter-data-jpa 1.3.3。除了调用merge()并传递用人对象之外,会话中没有其他工作要做。

以下是每个类的映射:

雇主

@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);
}

EmployerProductsPlan

@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对象的相同实例填充上述loyerProducts。它是瞬时的,并且没有填充ID,因为它尚不存在于数据库中。

EmployerProductsPlanId

@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。保存之前,永远不会从数据库加载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;
    }


}

1 个答案:

答案 0 :(得分:0)

到目前为止,我的解决方案是遍历EmployerProducts并检查新记录。在父Employer上调用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);
}