我无法使用hibernate在父实体中保存List <myentity>

时间:2016-06-20 09:11:50

标签: java hibernate jpa

我有两个实体

@Entity
@Table(name = "PP_CRM")
@EqualsAndHashCode(exclude={"id", "ppConfig"})
public class PricePlanCrm {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Getter @Setter private Long id;
    @Getter @Setter private String rkId;
    @Getter @Setter private String name;
    @Getter @Setter private String priceplantype;
    @Getter @Setter private String enabled;
    @ManyToOne()
    @JoinColumn(name = "PP_CONFIG_ID", nullable = false, updatable = true, insertable = true)
    @Getter @Setter private PricePlanConfig ppConfig;
}

@Entity
@Table(name = "PP_CONFIG")
public class PricePlanConfig {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    @Getter @Setter private Long id;
    @Getter @Setter private String Name;
    @Getter @Setter private String wfaId;
    @Getter @Setter private Integer status;
    @OneToMany(mappedBy = "ppConfig", fetch = FetchType.EAGER,  cascade = CascadeType.ALL , orphanRemoval = true)
    @Getter @Setter private List<PricePlanCrm> ppCrm;
}

我希望将PricePlanConfig保存为PricePlanCrm列表,所有已保存但PP_CONFIG_ID列未ID PricePlanConfig

这是我的保存方法

public void savePricePlanConfig(){
        PricePlanConfig pricePlanConfig = new PricePlanConfig();
        pricePlanConfig.setName(pricePlanConfigName);
        pricePlanConfig.setWfaId(workFlowId);
        int status = Boolean.parseBoolean(isActive) ? 1 : 0;
        pricePlanConfig.setStatus(status);
        List<PricePlanCrm> pricePlansClear = getPricePlansClear();
        pricePlanConfig.setPpCrm(pricePlansClear);
        PricePlanConfigDaoImpl.me().persist(pricePlanConfig);
        clearForm();
    }

后续保存我有两个表但在PP_CRM表中我有PP_CONFIG_ID列,其中所有值都是EMPTY

修改

我在行中使用nullable = false

@JoinColumn(name = "PP_CONFIG_ID", nullable = false, updatable = true, insertable = true)

我有错误

org.hibernate.PropertyValueException: not-null property references a null or transient value : crm.entity.PricePlanCrm.ppConfig

如果我将其添加到我的保存方法

for (PricePlanCrm pricePlanCrm : pricePlansClear) {
            pricePlanCrm.setPpConfig(pricePlanConfig);
        }

所有ID保存正常,但我认为这是不好的实践,而且hibernate必须自动保存。我认为? hibernate在保存PricePlanCrm之前尝试保存PricePlanConfig entyty并尝试将PricePlanConfig设置为PricePlanCrmPricePlanConfig尚未保存且为空。我认为hibernate必须在PricePlanCrm(子)之前保存PricePlanConfig(它是Parent),但这不是真的

1 个答案:

答案 0 :(得分:0)

PricePlanCrm

你必须提到你的targetEntity

@ManyToOne(targetEntity = PricePlanConfig .class)
    @JoinColumn(name = "PP_CONFIG_ID", nullable = false, updatable = true, insertable = true)
    @Getter @Setter private PricePlanConfig ppConfig;
PricePlanConfig中的

尝试使用targetEntity

@OneToMany(mappedBy = "ppConfig",targetEntity = PricePlanCrm.class, fetch = FetchType.EAGER,  cascade = CascadeType.ALL , orphanRemoval = true)
    @Getter @Setter private List<PricePlanCrm> ppCrm;