Issue
In a Service I want to set the betrag for a BudgetGeschaeftfeld. After setting the Betrag, a method of budgetPlan which is Fetch.Eager should be called to update its own Betrag. However I get a NullPointerException
java.lang.NullPointerException: Cannot invoke "com.bm.ent.budgetplan.BudgetPlan.berechnePrognose()" because "this.budgetPlan" is null
why is this happening? and what can I do to solve it?
my Class code:
@Entity(name= "Budgetgeschaftsfeld")
@Getter
@Setter
@NoArgsConstructor
public class BudgetGeschaeftsfeld extends Budget{
@JsonIgnore
@OneToMany(
mappedBy="budgetGeschaftfeld",
cascade=CascadeType.ALL,
orphanRemoval=true,
targetEntity = BudgetMarke.class
)
private List<BudgetMarke> childBudgets= new ArrayList<>();
@JsonIgnore
@ManyToMany
@ToString.Exclude
private List<User> users= new ArrayList<>();
@JsonIgnore
@ManyToOne( fetch=FetchType.EAGER,
cascade=CascadeType.PERSIST)
@JoinColumn(name="pid")
@ToString.Exclude
private BudgetPlan budgetPlan;
public BudgetGeschaeftsfeld(String name, BudgetTyp typ, Double betrag, String kommentar) {
super(name, typ, betrag, kommentar);
}
public void setBetrag(Double betrag) {
if (this.getBudgetTyp()==BudgetTyp.DYNAMISCH) {
super.setBetrag(this.betragChildBudgets());
}else {
super.setBetrag(betrag);
}
budgetPlan.berechnePrognose();
}
Solution
The answer was
@JsonIgnore
@ManyToOne( fetch=FetchType.Lazy,
cascade=CascadeType.PERSIST)
@JoinColumn(name="pid")
@ToString.Exclude
private BudgetPlan budgetPlan;
and then getting the budgetplan before calling the method
public void setBetrag(Double betrag) {
if (this.getBudgetTyp()==BudgetTyp.DYNAMISCH) {
super.setBetrag(this.betragChildBudgets());
}else {
super.setBetrag(betrag);
}
detBudgetPlan().berechnePrognose();
}
Answered By - Nortap
Answer Checked By - David Goodson (JavaFixing Volunteer)